简体   繁体   中英

How to intercept a submit button click?

I have a form and a submit button.

I want to do a quick check on some of the fields (if one isn't filled in, then to blank some of the others).

I would rather not change the HTML for the button, I would like to just to do this in jQuery and not add any "onclick" attributes to the button.

HTML:

<input class="cssButton button_in_cart" type="submit" value="Add to Bag" style="width: 80px;">

jQuery (attempted):

$("input.button_in_cart").mousedown(function () {
    alert("clicked");   
});

This doesn't work, it still submits the form without showing the alert. Thanks.

Do not use any form of click event for form processing as keyboard submission will bypass your code!

Use the submit event handler instead and return false (or e.preventDefault() ) to stop the submit proceeding.

eg

$('#myform').submit(function(e){
   // Do your validation here
   // ...
   // Then conditionally stop the submit from firing
   if (someValidateFails){
      e.preventDefault()
   }
});

make type as 'button' first

<input class="cssButton button_in_cart" type="submit" value="Add to Bag" style="width: 80px;">


$("input.button_in_cart").mousedown(function (e) {
   e.preventDefault();
    alert("clicked");   
    // do the form submit
   document.forms[0].submit();
});

You can use the return value of the function to prevent the form submission

<form name="myForm" onsubmit="return validateMyForm();"> 

and function like

<script type="text/javascript">
function validateMyForm()
{
  if(check if your conditions are not satisfying)
  { 
    alert("validation failed false");
    returnToPreviousPage();
    return false;
  }

  alert("validations passed");
  return true;
}
</script>

In case of Chrome 27.0.1453.116 m if above code does not work, please set the event handler's parameter's returnValue field to false to get it to work.

There are two main ways to "stop" an event. The first one is to return false; and the other one is to e.preventDefault(); . Teh difference in these two ways is that using e.preventDefault(); will stop the entire event from proceeding and won't propagate the DOM.

I would use the following:

$("input.button_in_cart").mousedown(function () {
    alert("clicked");   
    return false;
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM