Reputation: 20041
jQuery allows to trigger a form submission programmatically via either:
$('.js-form-class-hook').submit();
$('.js-form-class-hook').trigger('submit');
Note: My understanding is that .trigger('submit')
is to .submit()
what .on('submit',function(e){});
is to .submit(function(e){});
. In short .trigger('submit')
is a more powerfull way than .submit()
to programmatically submit forms .
I already know some of the difference between .on('submit',function(e){});
and .submit(function(e){});
, see my answer on What's the difference between $(form).submit and $(form).on("submit") in jQuery? , I would like to now understand better the role of .trigger('submit')
.
My conclusion: after some research I found out that using .trigger('submit')
seems to provide the "only" (although very powerful) advantage of allowing to pass arbitrary data
Sample usage 1:
This can for instance be used to differenciate a "human" vs "programmatical" form submission.
see live demo (click on Run/Clear in the top-right) on jsbin.com/jivexawixonu/1/edit?html,js,console,output
HTML
<form class="js-form-hook-xyz">
<button>Submit form</button>
</form>
jQuery
var pleaseConfirmSubmission = function( formElem ){
// ... some conditions checks
// if condition met, submit with a flag
formElem.trigger( "submit" , ['isProgrammaticalSubmission'] );
}
$("body").on("submit", ".js-form-hook-xyz", function(event, isProgrammaticalSubmission) {
console.log("on form submission: " + ( isProgrammaticalSubmission || "isHumanAction !" ) );
if ( !isProgrammaticalSubmission ){ /* JS truthy/falsy value usage */
event.preventDefault(); /* cancel form submission */
pleaseConfirmSubmission( $(this) );
}
});
Resources:
Is there any other additional feature provided by .trigger('submit')
that I missed ?
Or is "allowing to pass arbitrary data" the only advantage of using .trigger('submit')
?
Upvotes: 3
Views: 2415
Reputation: 36784
There is essentially no different between submit()
without an argument, and trigger('submit')
, in fact submit()
with no arguments will eventually return trigger()
anyway.
You can prove this by looking at the jQuery Source:
jQuery.fn.submit()
function (data, fn) {
return arguments.length > 0 ? this.on(name, null, data, fn) : this.trigger(name);
}
So, if an argument is passed to submit()
, .on('submit'...
will be called, otherwise, .trigger('submit')
will be called.
submit()
is pretty much a more human-readable way of calling trigger('submit')
. There are no special features for either, which one you choose is personal preference.
Note: The same goes for click()
, change()
etc..
is "allowing to pass arbitrary data" the only advantage of using .trigger('submit') ?
Unless you consider one less function call an advantage, yes, it is.
Upvotes: 5