JQuery methods: difference between .submit () vs .trigger ('submit')
jQuery allows you to trigger a form submission programmatically via:
-
$('.js-form-class-hook').submit();
-
$('.js-form-class-hook').trigger('submit');
Note. I understand that .trigger('submit')
corresponds .submit()
that .on('submit',function(e){});
corresponds .submit(function(e){});
. In short, it .trigger('submit')
is more powerful than .submit()
submitting forms programmatically.
I already know some difference between .on('submit',function(e){});
and .submit(function(e){});
, see my answer at What is the difference between $ (form) .submit and $ (form) .on ("submit") in jQuery? , I would like to better understand the role .trigger('submit')
.
My takeaway: After some research, I figured out that the use .trigger('submit')
seems to provide the "only" (albeit very powerful) advantage of allowing arbitrary data to be passed
Use case 1:
This can be used, for example, to distinguish between " human " and " software ".
see live demo (click "Run / Clear" in the upper right corner) at 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 another additional feature provided .trigger('submit')
that I missed?
Or "allows arbitrary data transfer" is the only benefit of using it .trigger('submit')
?
source to share
There is essentially no distinction between submit()
no argument, and trigger('submit')
in fact submit()
no argument will eventually return trigger()
.
You can prove it by looking at 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()
, it will be called .on('submit'...
, otherwise it will be called .trigger('submit')
.
submit()
is a much more human-readable way of calling trigger('submit')
. There are no special features for them that you choose, these are personal preferences.
Note: The same applies to click()
, change()
etc.
"allows you to pass arbitrary data" the only benefit of using .trigger ('submit')?
Unless you think that one function call is less, yes it is.
source to share