0

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?

3 Answers 3

2

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));
Sign up to request clarification or add additional context in comments.

1 Comment

Is this complete? He is passing $form.submit instead of $form.get(0).submit - I cannot test my idea because a plugin is adding stuff to the forms
0

Your code be. Just pass the object is enough.

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

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

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

  MyMethod(form);
})

1 Comment

That ties MyMethod strictly to forms. In my case (a dialog box) I simply want to execute the function passed to it, not necessarily a form object. It's my bad, I shouldn't have named the parameter formSubmit, instead simply func, I'll update my code.
-1

Without the parentheses, .submit would just be a property of the jQuery object that you have. In this instance, your form.

Adding the parentheses actually calls the .submit() method on the form object.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.