Form Handlers

Forms are Objects; they have their own Methods, Properties, and Event Handlers. One Event Handler that you should know about is onSubmit.

onSubmit can called in one of 3 ways:

  • by the user pressing Enter (Return) in a text field, or
  • if a user clicks on a Submit button, or
  • by using the submit() method.

If these actions are not handled in some way, your JavaScript may behave differently than expected. Try clicking on Submit below and see what happens. Also checkout the URL Address, what do you notice?

<FORM>
    
     <INPUT TYPE="submit" VALUE="Submit">
</
FORM>

Clicking on an un-handled Submit button generally leads to reloading the page. In general, you won't want this. In order to block this behavior, you need to do this:

    <FORM onSubmit="return false;">
         <INPUT TYPE="submit" VALUE="Submit">
    </FORM>

Try it:

Generally, return false is a way that JavaScript stops your browser from doing what it would otherwise do. Another example of this is stopping an href from going to the URL assigned to it. For example, the link

    <A HREF="http://sislands.com/coin70" onClick="return false;">
    JavaScript!
    </A>

won't go anywhere because you've returned false on the onClick. Click on this dead link, if you don't believe me.

function txtbox(form) {
     form.textbox.value += 'blahblahblah ' 
}

<A HREF="javascript:txtbox(document.EntryForm)"
  onMouseOver="status='Dead Link Demo'; return true;"
  onMouseOut="status='';">
Click on this dead link &amp; see what happens
</A>

Click on this dead link & see what happens

Let's see what happens:

This may seem like a weird thing to do, but actually it's quite common, especially in the case of forms. Here's an example of using a form to get input from a user. Type something into this text field and hit Enter (Return):

Here's the form:

    <FORM NAME="EntryForm" onSubmit="txtbox(this); return false;">
         <B>Let's see what happens: </B>
         <INPUT TYPE="text" NAME="textbox">
    </FORM>

When you hit Enter (Return) in the text field, the onSubmit Handler gets called. It executes the function txtbox(), which changes the value in the text field.

If the return false wasn't in the onSubmit Handler, the function txtbox() would execute, changing the text field, but then the page would reload, changing the text field back to what it was. To stop this from happening, you need to have that return false in the onSubmit.

    function txtbox(form) {
         form.textbox.value += 'blahblahblah ';
    }

Click on this "non"-dead link & see what happens

And here's an example of the same form without the return false, just so you can see what happens:

Let's see what happens:

I hope you've convinced yourself of the merits of return false.