Silviu Postavaru
Silviu Postavaru

Reputation: 1794

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

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?

Thanks!

//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

Upvotes: 6

Views: 8116

Answers (2)

Felix Kling
Felix Kling

Reputation: 816364

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

Upvotes: 8

Benubird
Benubird

Reputation: 19477

In short, no. If you have two event handlers, then you have two event handlers. That said however, there are ways around it.

First, remember that javascript execution is single-threaded. If you define a global variable, say var haveCalledSubmit=0;, then you can use that to synch your handlers. For example, if you start each handler function with this:

if(haveCalledSubmit == 1)return haveCalledSubmit = 0;
else haveCalledSubmit = 1;

Then only one of the two handlers will be called. You can easily modify it to match some condition, or to deal with more than two functions.

An alternative is to look into event propagation models. This page will give you all the information you need, although Felix has already mentioned an ajax command that may do what you want.

Upvotes: 2

Related Questions