1

I'm trying to define two eventhandlers for the same form in two different places.

modalPlaceholder.on('submit', 'form', function(e){
  var url = $(this).attr('action');
  var data = $(this).serialize();
  $.ajax({
    // ajax stuff
  });
  e.preventDefault();
})

This one to send the form via ajax post.

$('body').on('submit', 'form', function(){
  $(this).find('.hasPlaceholder').each(function() {
    $(this).val('');
  });
})

This one to zero form values that are just placeholders, so they dont get sent to the server as actual values.

For forms, that are not within modalPlaceholder, this works fine. But for forms that I want to send with ajax, the form gets serialized and sent before the zeroing happens.

Is there a way to define an order in which the eventhandlers get called? Help much appreciated.

Tilman Koester
  • 1,739
  • 2
  • 11
  • 25
  • 1
    Have a look at this, it might help: http://stackoverflow.com/questions/2360655/jquery-event-handlers-always-execute-in-order-they-were-bound-any-way-around-t – Bogdan Feb 21 '12 at 13:07
  • Thanks for your comment. The problem is, that technically I dont attach both eventhandlers to the same element. First one is attached to body and the second one to modalPlaceholder. But your link might still prove to be useful. – Tilman Koester Feb 21 '12 at 13:20
  • Frédéric Hamidi's got it. You could also use the placeholder-attribute instead of your JS solution which doesn't require any clearing before form submission. – powerbuoy Feb 21 '12 at 13:37
  • The JS solution is just for browsers that dont support the placeholder attribute. – Tilman Koester Feb 21 '12 at 13:48

1 Answers1

3

You're delegating events to your modalPlaceHolder element and to the <body> element, respectively. It means the events have to reach these elements in order to be processed.

DOM events always bubble up the document hierarchy. Since your modalPlaceHolder element is a descendant of the page <body>, event bubbling will always reach it before the <body> element. Therefore, your first handler will always run before the second one, regardless of their registration order.

If at all possible, delegate both events either to the <body> element or to your modalPlaceHolder element, and register the second handler before the first:

$('body').on('submit', 'form', function() {
    $(this).find('.hasPlaceholder').val('');
}).on('submit', 'form', function(e) {
    var url = $(this).attr('action');
    var data = $(this).serialize();
    $.ajax({
        // ajax stuff
    });
    e.preventDefault();
});
Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
  • >If at all possible, delegate both events either to the element or to your modalPlaceHolder element I guess I will have to somehow MAKE it possible. Thanks for your insight. – Tilman Koester Feb 21 '12 at 13:50