问题
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.
回答1:
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()
}
});
回答2:
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.
回答3:
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();
});
回答4:
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;
})
来源:https://stackoverflow.com/questions/34064530/how-to-intercept-a-submit-button-click