Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org
#

Q155 What does "return false" do? When is it necessary? When is it not?

You are here: irt.org | FAQ | JavaScript | Misc | Q155 [ previous next ]

return false stops a form from being submitted. For example the following form will not be submitted:

<FORM>
<INPUT TYPE="BUTTON" VALUE="Click Me">
</FORM>

However the following form will:

<FORM>
<INPUT TYPE="SUBMIT" VALUE="Click Me">
</FORM>

That last form will actually result in the page being reloaded.

To trap the submission of the form, for example to validate the form fields, you can use the onSubmit event handler:

<FORM onSubmit="someFunctionName()">
<INPUT TYPE="SUBMIT" VALUE="Click Me">
</FORM>

If the form validation is supposed to stop the form from being submitted then it has to return false from the event handler: onSubmit="return false"

The way this is normally doen is for the function to either return true or false:

<SCRIPT LANGUAGE="JavaScript"><!--
myFunctionName() {
    if (document.myForm.myText.value == '')
        return false;
    else
        return true;
}
//--></SCRIPT>

<FORM NAME="myForm" onSubmit="return myFunctionName()">
<INPUT TYPE="TEXT" NAME="myText">
<INPUT TYPE="SUBMIT" VALUE="Click Me">
</FORM>

The above form will only submit if the text field has some data. The function returns either true or

©2018 Martin Webb