Reputation: 25553
In a MVC view, I have a form as below. when user click on the submit button, I want to check somthing firstly. If it is ok, submit the form. If not pass the checking, give user a alert message, then stay in the view. My sample code as:
<script type="text/javascript">
function CheckingStatus() {
//.....
if (answer == "N") {
alert("You choose No.");
return false;
}
}
</script>
<% Html.RenderPartial("MyForm"); %>
....
<input id="btnSubmit" type="submit" value="Submit" onclick="CheckingStatus();" />
<% } %>
But when testing, even answer=="N", the form is still submitted. How to stop the form submitting ?
Upvotes: 13
Views: 23791
Reputation: 18113
Another way it can be done:
document.forms['MyForm'].onsubmit = CheckingStatus;
Upvotes: 7
Reputation: 2725
I would use an ASP.NET button, OR add the runat="server" property to the HMTL button then use the UseSubmitBehavior="false" property to disable postback / form submission. You can then call form.Submit(); or similar in your JavaScript.
Upvotes: 0
Reputation: 126547
Change your code to:
<input id="btnSubmit" type="submit" value="Submit" onclick="return CheckingStatus();" />
Note I added the word "return".
Upvotes: 6
Reputation:
try changing
<input id="btnSubmit" type="submit" value="Submit" onclick="CheckingStatus();" />
to
<input id="btnSubmit" type="submit" value="Submit" onclick="return CheckingStatus();" />
Upvotes: 27