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:
- api.jquery.com/submit
- api.jquery.com/trigger
- api.jquery.com/on
- www.inkling.com/read/jquery-cookbook-cody-lindley-1st/chapter-8/recipe-8-5
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')
?