Chris Chris - 2 months ago 10
jQuery Question

Cannot pass jQuery form.submit() to another function to be executed

I have the following JavaScript:

function MyMethod(func)
{
func();
}

$('#Btn').on('click', function(e)
{
e.preventDefault();

var form = $(this).parent();

MyMethod(form.submit);
});


http://codepen.io/chrisnicholson/pen/YGxOdJ

This doesn't work, giving the following error in Chrome:

jquery.min.js:4 Uncaught TypeError: Cannot read property 'trigger' of undefined

If I modify the call to
MyMethod
to use the following then it works:

MyMethod(function(){
form.submit();
});


http://codepen.io/chrisnicholson/pen/amyRXX

Can someone explain why this is?

Answer

Ah, good ol' binding of this at work! If you only provide the method, it will not be called on the form but on the global object, like

submit.call(window) // resp. undefined in strict mode. Hence the error, I guess.

where what you want is

submit.call(form)

One way to fix this: Bind the submit method to the form:

MyMethod(form.submit.bind(form));