KentZhou
KentZhou

Reputation: 25553

How to stop the form submitting?

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

Answers (4)

Cleiton
Cleiton

Reputation: 18113

Another way it can be done:

document.forms['MyForm'].onsubmit = CheckingStatus;

Upvotes: 7

PortageMonkey
PortageMonkey

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

Craig Stuntz
Craig Stuntz

Reputation: 126547

Change your code to:

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

Note I added the word "return".

Upvotes: 6

user26901
user26901

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

Related Questions