Search code examples
javascriptasp.netwebformssubmit-button

Stop form submission when an html button with onserverclick enabled is clicked in an asp.net web App


I have a button in an asp.net application which submits a form.

    <input type="submit" id="sumbit" value="Sign up" runat="server" 
     onserverclick="sumbit_ServerClick2" class="submitbutton"/>

I have a javascript function which returns true and false. How do i prevent the form from being submitted if the javascript function returns false. I cant access the form tag as i am using masterpage and the whole contentplacedholder is enclosed within a runat="server" form.


Solution

  • Assuming your function is called yourJsFunction, I think you can just use onclick="return !!yourJsFunction();" on the input element, like this:

    <input type="submit" id="sumbit" value="Sign up" runat="server" onclick="return !!yourJsFunction();"
     onserverclick="sumbit_ServerClick2" class="submitbutton"/>
    

    Use !! in front of the function call to force a boolean value.

    --

    For ASP.NET Button use onClientClick="return !!yourJsFunction();".

    Read more here.