Thursday, November 01, 2007

Some tips about "Return false" on a javascript

Forms are objects; they have their own methods, properties, and event handlers. One event handler that you should know about is onSubmit.

onSubmit gets called in two situations: if a user clicks on a Submit button, or if a user hits Return in a text field. 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.

In Netscape, clicking on an unhandled 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://www.webmonkey.com/"
onClick="return false;">mattmarg!</a>

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

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 Return:

Who does the monkey love:

Here's the form:

<form name="text_entry_form" onSubmit="monkeyLove(); return false;">
<b>Who does the monkey love: </b>
<input type="text" name="monkey_love" size="30">
</form>

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

If the return false wasn't in the onSubmit handler, the function monkeyLove() 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.

Here's the monkeyLove() function for your perusal:

function monkeyLove()
{
  var who_it_is = window.document.text_entry_form.monkey_love.value;
  who_it_is = 'The monkey loves ' + who_it_is;
  window.document.text_entry_form.monkey_love.value = who_it_is;
}

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

Who does the monkey love:

 

Reference: http://www.webmonkey.com/webmonkey/98/04/index3a_page5.html?

 

 

No comments: