This is probably not your usual "How do I capture form submit events?" question.
I'm trying to understand precisely how form submit events are handled by jQuery, vanilla Javascript, and the browser (IE/FF/Chrome/Safari/Opera) -- and the relationships between them. (See my other question.) After hours of Googling and experimenting, I still cannot come to a conclusion, either because of discord or vagueness.
I'm finishing up a script which integrates with website forms so that the forms can't be submitted until an AJAX request comes back.
Ideally:
My current understanding is that: (these may be wrong, please correct me if so)
click
eventsclick
events (whether in the markup like onclick=""
or bound using jQuery) are executed firstsubmit
events (whether in the markup like onsubmit=""
or bound using jQuery) are executed next$('[type=submit]').click()
doesn't invoke the form's submit
event, so its handlers don't get called$('form').submit()
doesn't invoke the submit button's click
event, so its handlers don't get calledsubmit
event... (but as mentioned above, invoking click on the submit button doesn't do the same)submit
event are called...Right now, I am:
click
event while preserving a reference to themclick
event, so it executes firstonclick=""
and onsubmit=""
(on their respective elements) and re-binding them using jQuery (so they execute after mine), then setting the attributes to null
Actually, this has been remarkably effective in my own testing, so that my event handler fires first (essential).
The problem, and my questions:
My handler fires first, just as expected (so far). The problem is that my handler is asynchronous, so I have to suppress (preventDefault/stopPropagation/etc) the form submit
or submit button click
event which invoked it... until the API request is done. Then, when the API request comes back, and everything is A-OK, I need to re-invoke the form submit automatically. But because of my observations above, how do I make sure all the event handlers are fired as if it were a natural form submit?
What is the cleanest way to grab all their event handlers, put mine first, then re-invoke the form submit so that everything is called in its proper order?
And what's the difference, if any, between $('form').submit()
and $('form')[0].submit()
? (And the same for $('[type=submit]').click()
and $('[type=submit]')[0].click()
)
tl;dr, What is the canonical, clear, one-size-fits-all documentation about Javascript/jQuery/browser form-submit-event-handling? (I'm not looking for book recommendations.)
Some explanation: I'm trying to compensate for a lot of the Javascript in shopping cart checkout pages, where sometimes the form is submitted only when the user CLICKS the BUTTON (not a submit button) at the bottom of the page, or there are other tricky scenarios. So far, it's been fairly successful, it's just re-invoking the submit that's really the problem.
Bind to the form's submit handler with jQuery and prevent the default action, then, when you want to submit the form, trigger it directly on the form node.
$("#formid").submit(function(e){
// prevent submit
e.preventDefault();
// validate and do whatever else
// ...
// Now when you want to submit the form and bypass the jQuery-bound event, use
$("#formid")[0].submit();
// or this.submit(); if `this` is the form node.
});
By calling the submit
method of the form node, the browser does the form submit without triggering jQuery's submit handler.
These two functions might help you bind event handlers at the front of the jquery queue. You'll still need to strip inline event handlers (onclick
, onsubmit
) and re-bind them using jQuery.
// prepends an event handler to the callback queue
$.fn.bindBefore = function(type, fn) {
type = type.split(/\s+/);
this.each(function() {
var len = type.length;
while( len-- ) {
$(this).bind(type[len], fn);
var evt = $.data(this, 'events')[type[len]];
evt.splice(0, 0, evt.pop());
}
});
};
// prepends an event handler to the callback queue
// self-destructs after it's called the first time (see jQuery's .one())
$.fn.oneBefore = function(type, fn) {
type = type.split(/\s+/);
this.each(function() {
var len = type.length;
while( len-- ) {
$(this).one(type[len], fn);
var evt = $.data(this, 'events')[type[len]];
evt.splice(0, 0, evt.pop());
}
});
};
Bind the submit handler that performs the ajax call:
$form.bindBefore('submit', function(event) {
if (!$form.hasClass('allow-submit')) {
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();
// perform your ajax call to validate/whatever
var deferred = $.ajax(...);
deferred.done(function() {
$form.addClass('allow-submit');
});
return false;
} else {
// the submit event will proceed normally
}
});
Bind a separate handler to block click events on [type="submit"]
until you're ready:
$form.find('[type="submit"]').bindBefore('click', function(event) {
if (!$form.hasClass('allow-submit')) {
// block all handlers in this queue
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();
return false;
} else {
// the click event will proceed normally
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With