0

I have a javascript link that I'm using as a button on a popup:

<a href="#" class="submit-action close-modal">Submit</a>

The "submit-action" class has a jQuery .click() binding that performs a .submit() on the form that's embedded inside the modal. The "close-modal" class has a .click() binding that closes the modal.

$(".submit-action").click(function() ($("#someForm").attr("action", "someURL"); 
$("#someForm").submit();

this.close = function () {
    $("#modal").hide();
    $.unblockUI();
};

$(".close-modal").click(function()(this.close);

Currently, when I click this button, the close-modal binding seems to be executing first and closing the modal before the form is submitted. So the popup closes without performing the submit. Is there a way I can force the "submit-action" binding to execute first without combining the two .click() bindings?

user886596
  • 2,380
  • 5
  • 31
  • 53
  • You can't. Event handlers are not fired in a reliable order cross-browser. The only way to ensure that one thing happens after another is to utilize a callback provided for that handler by whatever 3rd-party library you're using. If they didn't build in a callback, then there's nothing you can do (Other than finding an alternative that's actually designed well to begin with). – Chris Pratt Aug 14 '12 at 14:48
  • possible duplicate of [How to order events bound with jquery](http://stackoverflow.com/questions/290254/how-to-order-events-bound-with-jquery) – mkoryak Aug 14 '12 at 14:49

3 Answers3

3

They fire in the order in which they are bound, so bind the close modal after you bind the submit action and it should go in the order you want.

Fiddle 1: http://jsfiddle.net/johnkoer/2xNwn/1/

Fiddle 2: http://jsfiddle.net/johnkoer/2xNwn/2/

From the JQuery documentation (emphasis mine):

By default, most events bubble up from the original event target to the document element. At each element along the way, jQuery calls any matching event handlers that have been attached. A handler can prevent the event from bubbling further up the document tree (and thus prevent handlers on those elements from running) by calling event.stopPropagation(). Any other handlers attached on the current element will run however. To prevent that, call event.stopImmediatePropagation(). (Event handlers bound to an element are called in the same order that they were bound.)

John Koerner
  • 37,428
  • 8
  • 84
  • 134
1

Simply having one above the other will cause it to happen first:

jsFiddle DEMO

$(document).on('click', '.submit-action', function () {
    alert('submit-action click');
});


$(document).on('click', '.close-modal', function () {
    alert('close-modal click');
});
Mark Pieszak - Trilon.io
  • 61,391
  • 14
  • 82
  • 96
0

If you want to close the modal just after the submit is completed. Trigger the action to close modal on "complete" event of the ajax.

Diego ZoracKy
  • 2,227
  • 15
  • 14