Cortina
Cortina

Reputation: 21

Why does an 'input submit' button prevent jQuery from submitting a form?

I had an 'input submit type' button on my form.

That button was submitting the form.

But when I added jQuery to do a dynamic submit it didn't work until I replaced the input submit button with a button element

<input type="submit" ...

to:

<button ....

What's the reason for that?

The dynamic form submit works fine now with the button element but it took me a while to figure out the cause.

Upvotes: 2

Views: 576

Answers (3)

Andrew Cooper
Andrew Cooper

Reputation: 32586

To do a dynamic submit with javascript you need to stop the default action of the Submit button from happening.

$(function () {
    $(':submit').click(function (event) {
        event.preventDefault();
        // submit the form dynamically
    });
});

Upvotes: 2

Phil
Phil

Reputation: 164892

Rather than attempting to catch click events on specific form elements, the most robust way to intercept form submission is using the form's submit event, eg

$("#form-id").submit(function() {
    var form = $(this);
    var action = form.attr('action');
    var method = form.attr('method');
    var data = form.serialize();

    /// you now have all the information required to
    /// perform a dynamic or AJAX form submission

    return false; // prevent default action
});

This method will not only catch click events on <input type="submit">, <input type="image"> and <button type="submit"> elements but will also work when the Enter key is pressed whilst focus is given to a text field.

Upvotes: 1

Ariel
Ariel

Reputation: 26773

You probably need to add onSubmit="return false;" in the form tag.

I can't give you a better answer than that without seeing your code.

Upvotes: 0

Related Questions