tags:

views:

245

answers:

4

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 ?

+6  A: 

try changing

<input id="btnSubmit" type="submit" value="Submit" onclick="CheckingStatus();" />

to

<input id="btnSubmit" type="submit" value="Submit" onclick="return CheckingStatus();" />
Scott Vercuski
+3  A: 

Change your code to:

<input id="btnSubmit" type="submit" value="Submit" onclick="return CheckingStatus();" />

Note I added the word "return".

Craig Stuntz
Thank you very much.
KentZhou
A: 

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.

PortageMonkey
This is MVC (see tags). There are no postbacks.
Craig Stuntz
+2  A: 

Another way it can be done:

document.forms['MyForm'].onsubmit = CheckingStatus;
Cleiton
This is useful when there happen to be several different ways in which a form can submit (e.g,. auto-postback drop-down list boxes, submit buttons, etc.). This way, you're guaranteed that the validation occurs without having to overwrite an input element's onclick handler.
David Andres
+1. The right place to put form validation/confirmation code is always form.onsubmit. And assigning it from JavaScript means you don't have the silly attribute value 'return ...' wrapper.
bobince