admin管理员组文章数量:1236540
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 e 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 es 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 es 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 remendations.)
Some explanation: I'm trying to pensate 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.
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 e 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 es 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 es 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 remendations.)
Some explanation: I'm trying to pensate 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.
Share Improve this question edited May 23, 2017 at 11:46 CommunityBot 11 silver badge asked Oct 19, 2012 at 16:32 MattMatt 23.8k18 gold badges74 silver badges116 bronze badges 9-
2
$('form').submit()
is not the same as$('[type=submit]').click()
. For example, the form submit handler catches a form submission when a user hits enter inside a text field and the click handler would not. – Sandro Commented Oct 19, 2012 at 17:09 - @Sandro Indeed, another plexity... – Matt Commented Oct 19, 2012 at 17:12
- I'm not really understanding the flow. The user has to click or submit the form twice? Once to validate through an API and once again to confirm and submit the form? Is there a way to split the two apart? API validation in one process and submitting the form in another? – Sandro Commented Oct 19, 2012 at 17:17
- @Sandro Sorry; the user only submits the form once. Once the API request is done, the user confirms the change to the input -- if needed -- then the form submit continues automatically, which is where I'm running into most of my problems (but not all). – Matt Commented Oct 19, 2012 at 17:21
-
1
$('[type=submit]')[0].click();
circumvents jQuery.$('[type=submit]')[0]
returns the DOM node and invokingclick
is calling the click function on the DOM node itself. – Sandro Commented Oct 19, 2012 at 18:21
4 Answers
Reset to default 8Bind 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
}
});
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.
$(function(){
var formSubmitQueue = 'formSubmitQueue';
//Here's a worker function that performs the ajax.
//It's coded like this to reduce bulk in the main supervisor Handler A.
//Make sure to return the jqXHR object that's returned by $.ajax().
function myAjaxHandler() {
return $.ajax({
//various ajax options here
success: function(data, textStatus, jqXHR) {
//do whatever is necessary with the response here
},
error: function(jqXHR, textStatus, errorThrown) {
//do whatever is necessary on ajax error here
}
});
}
//Now build a queue of other functions to be executed on ajax success.
//These are just dummy functions involving a confirm(), which allows us to reject the master deferred passed into these handlers as a formal variable.
$("#myForm").on(formSubmitQueue, function(e, def) {
if(def.state() !== 'rejected') {
if (!confirm('Handler B')) {
def.reject();
}
}
}).on(formSubmitQueue, function(e, def) {
if(def.state() !== 'rejected') {
if (!confirm('Handler C')) {
def.reject();
}
}
}).on(formSubmitQueue, function(e, def) {
if(def.state() !== 'rejected') {
if (!confirm('Handler D')) {
def.reject();
}
}
});
$("#myForm").on('submit', function(e) {
var $form = $(this);
e.preventDefault();
alert('Handler A');
myAjaxHandler().done(function() {
//alert('ajax success');
var def = $.Deferred().done(function() {
$form.get(0).submit();
}).fail(function() {
alert('A handler in the custom queue suppressed form submission');
});
//add extra custom handler to resolve the Deferred.
$form.off(formSubmitQueue+'.last').on(formSubmitQueue+'.last', function(e, def) {
def.resolve();
});
$form.trigger(formSubmitQueue, def);
}).fail(function() {
//alert('ajax failed');
});
});
});
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.
$("#myForm").on(formSubmitQueue, function(e, def) {
if(def.state() !== 'rejected') {
//actions as required here
if (expression) {
def.reject();
}
}
});
Pattern 2:
Performs its actions only if all preceding handlers have not rejected def. but does not suppress following handlers.
$("#myForm").on(formSubmitQueue, function(e, def) {
if(def.state() !== 'rejected') {
//actions as required here
}
});
Pattern 3:
Performs its actions unconditionally but can still suppresses all following handlers of Pattern 1 and Pattern 2.
$("#myForm").on(formSubmitQueue, function(e, def) {
//actions as required here
if (expression) {
def.reject();
}
});
Pattern 4:
Performs its actions unconditionally, and does not suppress following handlers.
$("#myForm").on(formSubmitQueue, function(e, def) {
//actions as required here
});
Notes:
- The deferred could be resolved in these handlers in order to submit the form immediately without processing the rest of the queue. But in general, the deferred will be resolved by the '.last' handler added to the queue dynamically before the queue is triggered (back in Handler A).
- In the Demo, all the handlers are of Pattern 1.
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 prehensive 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 the jquery.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. (checkout) and MedicalCareAlert. (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.
var oldHandlers, eventsRef = $._data(this, 'events');
// If there are previously-bound-event-handlers (from jQuery), get those.
if (eventsRef && eventsRef.click && eventsRef.click.length > 0)
{
// Get a reference to the old handlers previously bound by jQuery
oldHandlers = $.extend(true, [], eventsRef.click);
}
// Unbind them...
$(this).unbind('click');
// ... then bind ours first ...
$(this).click({ form: f, invoke: this }, submitHandler);
// ... then bind theirs last:
// First bind their onclick="..." handles...
if (typeof this.onclick === 'function')
{
var temp = this.onclick;
this.onclick = null;
$(this).click(temp);
}
// ... then finish up with their old jQuery handles.
if (oldHandlers)
for (var j = 0; j < oldHandlers.length; j++)
$(this).click(oldHandlers[j].data, oldHandlers[j].handler);
本文标签:
版权声明:本文标题:javascript - How can I correctly capture and re-fire the form submit event, guaranteed? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1739822141a2195330.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论