1

This is such a simple thing, or so I thought. But I just don't get why this is happening...

jQuery's .submit() method. Seems easy enough – pass it a function and that serves as the listener. Don't pass it anything and it calls .trigger('submit'). But it's been a huge headache for me over the past 24 hours.

Basically what I'm trying to do is build a simple validation script. The user clicks the submit button on a form, a function runs to validate the inputs, and if all is good in the world, the form submits (the default way, no fancy ajax in this scenario). The issue comes in when trying to call .submit on either the jQuery object or just the plain 'ole HTML DOM element object. I've learned that jQuery kills the native .submit on HTMLFormElement, so it makes sense why that doesn't work (I guess, but that seems dumb). But... why wouldn't jQuery's .trigger('submit') (or .submit() for short) work?

Example (or take a look at the Fiddle):

HTML:

<form class="comment-form" action="#" method="get">
    <input type="submit" id="submit" name="submit" value="submit"/>
</form>

JavaScript:

$('.comment-form').on('click', '#submit', function(e) {
    var form = e.delegateTarget;

    e.preventDefault();

    // For the purpose of demonstration, just setting it true
    if (true) {
        form.submit(); // object is not a function - this makes sense since jQuery is overriding this
        $(form).submit(); // nothin at all :(
        $(form).trigger('submit'); // nope, nada
    }
});

I did find a workaround by calling the form using .call() on the HTMLFormElement prototype, but why should I have to do this?

Why? Why? Why?

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
SeeMeCode
  • 1,415
  • 15
  • 19

1 Answers1

3

You named your button submit, so form.submit is now the button, not the submit function.
In other words, you've just removed the native submit function and replaced it with your button, which is why you're getting the error "object is not a function".

Change the name of the button to something other than submit, and it will work.

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • just remove the `$(form).trigger('submit');` from fiddle – Runcorn Jul 23 '14 at 16:38
  • I feel like a bit of an idiot, but thank you @adeneo. Figured it was something simple, but hopefully this will help others from running into the same issue! – SeeMeCode Jul 23 '14 at 17:03
  • @SeeMeCode - It's actually a hard error to spot, so don't feel like an idiot, and you're not the first one to do it. – adeneo Jul 23 '14 at 17:54