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:
- User fills out form
- Form is submitted -- but no previously-bound event handlers are called, except mine
- My handler makes an API request (asynchronously, of course)
- User confirms validation results from API response
- Form submit continues normally, automatically, invoking the other handlers which before were suppressed
My current understanding is that: (these may be wrong, please correct me if so)
- jQuery binds form submit event handlers to the submit button
click
events - Event handlers directly on the submit element
click
events (whether in the markup likeonclick=""
or bound using jQuery) are executed first - Event handlers on the form
submit
events (whether in the markup likeonsubmit=""
or bound using jQuery) are executed next - Calling
$('[type=submit]').click()
doesn't invoke the form'ssubmit
event, so its handlers don't get called - Calling
$('form').submit()
doesn't invoke the submit button'sclick
event, so its handlers don't get called - Yet somehow, a user that clicks the submit button ends up invoking handlers bound to the form's
submit
event... (but as mentioned above, invoking click on the submit button doesn't do the same) - In fact, any way the user submits the form (via submit button or hitting Enter), handlers bound with jQuery to the form
submit
event are called...
Right now, I am:
- Unbinding handlers bound with jQuery to the submit button's
click
event while preserving a reference to them - Binding my own handler to the submit button's
click
event, so it executes first - Taking any handlers bound in the markup using
onclick=""
andonsubmit=""
(on their respective elements) and re-binding them using jQuery (so they execute after mine), then setting the attributes tonull
- Re-binding their handlers (from step 1) so they execute last
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.
There must be many ways to address this - here's one.
It keeps your ajax function (A) separate from all the others (B, C, D etc.), by placing only A in the standard "submit" queue and B, C, D etc. in a custom event queue. This avoids tricky machinations that are otherwise necessary to make B, C, D etc. dependent on A's asynchronous response.
DEMO (with simulated ajax)
As an added bonus, any of the handlers in the custom queue can be made to suppress any/all following handlers, and/or suppress form submission. Just choose the appropriate pattern depending on what's required :
Pattern 1:
Performs its actions only if all preceding handlers have not rejected def. and can suppress all following handlers of Pattern 1 and Pattern 2.
Pattern 2:
Performs its actions only if all preceding handlers have not rejected def. but does not suppress following handlers.
Pattern 3:
Performs its actions unconditionally but can still suppresses all following handlers of Pattern 1 and Pattern 2.
Pattern 4:
Performs its actions unconditionally, and does not suppress following handlers.
Notes:
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.
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.Bind the submit handler that performs the ajax call:
Bind a separate handler to block click events on
[type="submit"]
until you're ready:Here's how I ended up doing this, and it has been very successful so far in numerous test cases. I learned an awful lot about events, particularly form submit events, in relation to jQuery. I don't have time to post a comprehensive encyclopedia of all the information I collected, but this will suffice for now:
This was for the SmartyStreets LiveAddress API jQuery Plugin which validates addresses before the user leaves the page.
The most successful method was by grabbing the submit button's
click
event. The snippet below is found in thejquery.liveaddress.js
file. It gets references to as many event handlers as possible (jQuery, onclick --- the onclick ones fire first), uproots them, plops down its own (submitHandler
), and layers the others on top of it. It's worked successfully on sites like TortugaRumCakes.com (checkout) and MedicalCareAlert.com (homepage and checkout) as well as many others.The full code is on GitHub. This particular segment goes for the "click" on the submit button, but similar code is used to handle form submit also. jQuery's
submit()
function seems to be rather proprietary... but this handling both ensures it gets called even when.submit()
is called programmatically on a jQuery object.