Question

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.

Was it helpful?

Solution 2

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.

OTHER TIPS

Use the onclick attribute to test the return value of your JS function:

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

Set the button type to "button" (defaults to submit), this will disable the submit of the form and rely upon the __doPostBack() to handle the wiring up.

<button id="MyButton" runat="server" type="button" onserverclick="MyButton_Click">Submit</button>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top