Javascript – Two submit event handlers on a form. One must stop the other

javascript, jquery

I have to event handlers attached to a form. The first one that fires should stop the other event if a condition is not met.

The code below does not work, as both events will be triggered. Can you help me?


//fires first$("#myform").submit(function(){  if (some validation) {    alert("You need to make the form valid");    return false;  }});//fires second$("#myform").submit(function(){  //ajax stuff  return false;});

p.s. I have to this as the ajax stuff is in a plugin that is not changeable. I cannot avoid two event handlers

Best Solution

Have a look at event.stopImmediatePropagation():

Keeps the rest of the handlers from being executed and prevents the event from bubbling up the DOM tree.

$("#myform").submit(function(event){  if (some validation) {    event.stopImmediatePropagation();    alert("You need to make the form valid");    return false;  }});

You might also want to use event.preventDefault().

Update: Just to clarify: You can rely on the order the event handlers are called. From jQuery's bind method:

When an event reaches an element, all handlers bound to that event type for the element are fired. If there are multiple handlers registered, they will always execute in the order in which they were bound. After all handlers have executed, the event continues along the normal event propagation path.

The order might not be defined in W3C's original definition but it works with jQuery. Otherwise, the above named function would be unnecessary anyway ;)