W3C home > Mailing lists > Public > www-html@w3.org > November 2004

Re: Question about which is the correct style of JavaScript to pass to FORM's onSubmit attribute

From: Sean Dockery <sdockery@securac.net>
Date: Mon, 15 Nov 2004 15:39:13 -0700
To: www-html@w3.org
Message-ID: <cnbb6j$uva$1@sea.gmane.org>

Thanks to all of you who have responded.

For posterity, below is the answer which I am taking to be correct:

>> Which is the following is correct?
>>
>> a) <form ... onSubmit="return checkData()">
>>
>> b) <form ... onSubmit="return checkData();">
>>
>> c) <form ... onSubmit="checkData()">
>>
>> d) <form ... onSubmit="checkData();">
>>
>> ...where checkData is a JavaScript function that returns a true or false 
>> value.
>
> All of them are correct in that they will result in the call of 
> checkData.  However, only a) and b) will actually affect whether the form 
> is submitted.
>
> The content of an intrinsic event attribute becomes the body of an 
> anonymous function:
>
>   /* Note that IE doesn't pass an event argument. It uses a global
>    * variable of the same name. Either way, you can still use:
>    *
>    *   on<event>="myFunction(event)"
>    *
>    * to access the event object.
>    */
>   formElement.onsubmit = function(event) {
>     /* Value in onsubmit attribute */
>   };
>
> Obviously, if you don't include a return statement, no value will 
> actually  be returned when this anonymous function exits.
>
> With regards to the semicolon, the same rules apply as normal: semicolons 
> are generally optional, but it's good practice to include them. If you 
> had  two or more statements/expressions to evaluate, a semicolon would be 
> necessary to separate them.
>
> The final point I like to make is that it's simpler to pass a reference 
> to  the FORM when it is called, rather than obtain one later. That is:
>
>   <form ... onsubmit="return checkData(this);">
>
>   function checkData(form) {
>     /* You can now use form, rather than
>      *   document.forms['formName']
>      */
>   }
>
>> It seems that Internet Explorer accepts all of the above, but I'm not 
>> taking that to mean that all are correct.
>
> As I said, they are all syntactically correct, but the second two are 
> probably not what you want.
>
> [snip]
>
> Hope that helps, 
Received on Monday, 15 November 2004 22:39:23 GMT

This archive was generated by hypermail 2.2.0+W3C-0.50 : Tuesday, 27 March 2012 18:16:01 GMT