开发者

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 wit开发者_StackOverflow中文版h 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.


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
    });
});


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜