I have a button in an asp 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.
I have a button in an asp 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.
Share Improve this question asked May 12, 2013 at 21:41 thunderbirdthunderbird 2,7335 gold badges29 silver badges53 bronze badges 1- 1 Is the javascript doing some type of validation? if so look into the validation controls to prevent postback. – fnostro Commented May 12, 2013 at 21:46
3 Answers
Reset to default 5Use 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;" />
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.
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>