Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning false in first of multiple form submission handlers

Tags:

jquery

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?

like image 571
Donald Taylor Avatar asked Feb 27 '12 19:02

Donald Taylor


People also ask

How do you avoid multiple form submissions?

Use JQuery to Prevent Multiple Form Submissions To prevent the user from submitting a form multiple times, we'll use JQuery to listen for the submission event. Once the form is submitted, we'll add a disabled attribute to the button to prevent multiple form submissions. Now the user can't click it again.

How can stop double click on submit button in JQuery?

attr('disabled', true). html("Processing...");" inside beforeSend() function on ajax. Then in the success() function on ajax a remove the disabled attribute/function so that the button will be clickable again after being submitted to the server.


1 Answers

Returning false from an event handler is the equivalent of calling both event.preventDefault() and event.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.

$("form").submit(function(event) {
  // perform validation here and set "validationFails" appropriately
  // ...
  if (validationFails) {
      event.stopImmediatePropagation();
      return false;
  }
});
like image 88
nnnnnn Avatar answered Oct 16 '22 14:10

nnnnnn