RSS

Javascript Return False Doesn’t Prevent Postback?

21 Apr

So, I have the following javascript function:

function SaveForm()
{
    // Check the required fields
    if (!formValidated()) {
        alert('Please complete the required fields.');
        return false;
    }
}

This function is called from HTML control (or ASP.Net Server control):

<input id="btnSave" name="btnSave" type="button" value="Save" onclick="SaveForm();" />

As you can see, the javascript supposed to check if the form validated and return false when the form is invalid. However, no matter what I do, the form will always submit and do a postback.

Well, in the case where we want to prevent form from submitting using javascript, not only do we need to “return false” in our javascript function, but we also need to add “return” keyword in our call to the function. So, to fix that, here’s my modified HTML control:

<input id="btnSave" name="btnSave" type="button" value="Save" onclick="return SaveForm();" />

Notice the “return” keyword before calling “SaveForm” function.

However, the “return” keyword (both in javascript function and HTML control) is not necessary if we use javascript “confim()” function:

function DeleteItem() {
    if (confirm("Are you really sure?")) {
        DeleteItemForSure();
    }
}
<input id="btnDelete" name="btnDelete" type="button" value="Delete" onclick="DeleteItem();" />
Advertisements
 
1 Comment

Posted by on April 21, 2011 in General

 

Tags: , ,

One response to “Javascript Return False Doesn’t Prevent Postback?

  1. DG

    April 4, 2013 at 6:40 am

    Thank you so much. This post really helped me!

     

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

 
%d bloggers like this: