I have two submit handlers, one validating a form and one submitting the form:
// validates the form but does not submit it
$("form").submit(function() {
// perform validation here and set "validationFails" appropriately
// ...
if (validationFails) {
return false;
}
});
// submits the form via ajax
$("form").submit(function(event) {
event.preventDefault();
// submit the form via ajax here
// ...
});
It seems like the form should not be submitted via ajax if validation fails because return false is used, and so the subsequent submit handler in the chain should not be called. However, even if validation fails, the form is submitted via ajax. Why?
Returning
falsefrom an event handler is the equivalent of calling bothevent.preventDefault()andevent.stopPropagation(), that is, it prevents the default action for the event from happening and it stops the event bubbling up the DOM tree. It does not stop other handlers on the same element from running.You need to call the
event.stopImmediatePropagation()method – that stops other handlers bound to the same element from running, noting that the handlers will be run in the same order they are bound so you (obviously) have to bind your validation handler first.