Categories:

onsubmit

The "onsubmit" handler is inserted inside the <form> tag, and not inside any one element, unlike "onblur." For example: <form name="george" onsubmit="what_ever"> Lets do an example:

Enter Your name (*required) If you leave the required sections blank, as you click submit, you will be forced to come back and fill this box in.

Feedback please: (*required)

Your home address (*NOT required)

<script type="text/javascript">
<!--
function validate(){
	if ((document.example2.naming.value=="") || (document.example2.feed.value=="")){
		alert("You must fill in all of the required fields!")
		return false
	}
	else
		return true
}
//-->
</script>

<form name="example2" onsubmit="return validate()">
<input type="text" size="20" name="naming">
<strong>Feedback please: (*required)</strong>
<textarea name="feed" rows="3" cols="25"></textarea>
<strong>Your home address (*NOT required)</strong>
<input type="text" size="35" name="address">
<input type="submit" name="B1" value="Submit">
</form>

Some every important things here:

  • document.example2.naming.value=="".What is the quotation in red? That is used to indicate an empty value- something that contains nothing. It is important that you distinguish between "" and " " The later means "1 empty space", as opposed to "empty value". The later is a char- namely, a space.
  • What is "return true", "return false"? This is what's used to actually allow, or stop the form from submitting, respectively. This is how JavaScript controls the submitting of a form. By default, a form will return true. (Submit the form). This is a important point- for example, by using the above knowledge, you can apply it to also stop a link from completing upon clicking. I'll show you an example:
    <a href="http://www.cssdrive.com" onclick="return false">Click here, it won't work!</a>
    Click here, it won't work!
    By returning false, we prohibit the action from completing!
  • Now, a confusing point may be-onsubmit="return validate()". Why return validate()? Wouldn't that be like a double return? No. Function validate only returns "true/false". You need "return true/fast" to actually manipulate whether a form submits or not. That's why we have to return validate(), as opposed to just validate().

Click here for a complete list of properties and methods of the Form object.