Attribute for <FORM ...>
onSubmit = "script command(s)"
Usage Recommendation |
use it, but don't rely on it |
onSubmit
is a scripting event that occurs when the user attempts to submit the form to the CGI. onSubmit
can be used to do some error checking on the form data, and to cancel the submit
if an error is found. For example, this
<FORM ...>
tag calls a Javascript function to check the form data:
<FORM
ACTION="../cgi-bin/mycgi.pl"
NAME="testform"
onSubmit="return TestDataCheck()"
>
Note that in order to cancel the submit event, the onSubmit
should be in the form
onSubmit="return
expression"
.
"return" indicates that the value of the expression should be returned to the submit routine. If the expression evaluates to false, the submit routine is cancelled; if it is true, the submit routine goes forward.
Let's look at the full code for our example. Consider a form that a technician uses to enter how
many production units have been tested, and how many units passed the tests. For a form like this we might want to check:
- if one or more units were tested
- if zero or more units were passed
- if no more units were passed than were tested
Here is the full code to do this:
<SCRIPT TYPE="text/javascript">
<!--
// check that they entered an amount tested, an amount passed,
// and that they didn't pass units than they more than tested
function TestDataCheck()
{
var qtytested = parseInt(document.testform.qtytested.value);
var qtypassed = parseInt(document.testform.qtypassed.value);
var returnval;
if ( (qtytested >= 1) && (qtypassed >= 0) && (qtytested >= qtypassed))
returnval = true;
else
{
alert("must enter the quantity tested and that amount or fewer for quantity passed");
returnval = false;
}
return returnval;
}
// -->
</SCRIPT>
<FORM
ACTION="../cgi-bin/mycgi.pl"
NAME="testform"
onSubmit="return TestDataCheck()"
>
units tested: <INPUT NAME="qtytested" SIZE=3><BR>
units passed: <INPUT NAME="qtypassed" SIZE=3><P>
<INPUT TYPE=SUBMIT VALUE="Submit">
</FORM>
which gives us this form:
onSubmit
is a good way to prescreen the data on a form before it is submitted to the CGI, but like
anything Javascript, it shouldn�t be relied on. Be sure to error check the data in your CGI program also.