javascriptjqueryhtmlasp.netpostbackurl

How to stop a page from loading with JavaScript


I have a Button with PostBackUrl. Also I have assigned a function to its onclientclick method in which some page logic were written including a couple of validation rules. if whole page were not valid this method returns False but I can not stop page. I have tried document.execCommand('Close') and Window.Stop() but no success.

Any suggestions?

Edit: Button:

<asp:Button ID="btnSubmit" runat="server" OnClientClick="return DoLogic()"  PostBackUrl="http://google.com" Class="btn_submit"/>

DoLogic:

function DoLogic() {

if (ValidateForm()) {
blah blah blah
return true;
}
else {
alert("Has Error");
return false;
}

ValidateForm:

function ValidateForm(){
if (haserror)  
{  
return false; 
} 
return true; 
}

Solution

  • You can use .preventDefault() method on your event. This will stop the default action of a page load when the button is clicked.

    http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-flow-cancelation

    You can also return false; inside your DoLogic(). This will stop the page load as well.

    onclientclick="return DoLogic()"
    

    Then in your function:

    function DoLogic(){
        //blah blah blah
        return false;
    }
    

    UPDATE

    If you're doing all of this and are still having problems, try adding this to your button:

    onclick="javascript:return false"
    

    UPDATE FROM OP

    Your code isn't working because in the if statement you return true; and false only gets returned if the shit hits the fan (ie an error). You need to return false everytime. OR use the .preventDefault() like I mentioned earlier.