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.

Answers


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.

e.g.

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

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.


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();
});

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;
})

Need Your Help

org.apache.commons.fileupload.servlet.ServletFileUpload does not seem to have method setProgressListener

java servlets file-upload apache-commons

The class org.apache.commons.fileupload.servlet.ServletFileUpload does not seem to have method setProgressListener in commons-fileupload version 1.2 or 1.2.2, yet it is referenced in examples provi...

What does static and IOException mean?

java

I just had a test on java and we had to give the definition of