Home >Web Front-end >JS Tutorial >How to Prevent Double Form Submission in jQuery?

How to Prevent Double Form Submission in jQuery?

DDD
DDDOriginal
2024-11-10 08:14:02777browse

How to Prevent Double Form Submission in jQuery?

Preventing Form Resubmission in jQuery

In form submission, it's crucial to prevent users from accidentally submitting twice during a server processing delay. A common solution involves disabling form elements upon submission. However, this approach may disable elements that shouldn't be, such as inputs containing essential data.

Disable Only Submit Buttons

To specifically disable submit buttons and avoid interfering with form submission, use the following code:

$('button[type=submit], input[type=submit]').prop('disabled',true);

jQuery Plugin for Double Submission Prevention

Another effective solution is to create a jQuery plugin that utilizes the data() function to mark forms as already submitted:

jQuery.fn.preventDoubleSubmission = function() {
    $(this).on('submit',function(e){
        var $form = $(this);

        if ($form.data('submitted') === true) {
            // Previously submitted - don't submit again
            e.preventDefault();
        } else {
            // Mark it so that the next submit can be ignored
            $form.data('submitted', true);
        }
    });

    // Keep chainability
    return this;
};

To use the plugin, simply apply it to your form:

$('form').preventDoubleSubmission();

Excluding Ajax Forms

If you have AJAX forms that require multiple submissions, exclude them by adding a class and using the following selector:

$('form:not(.js-allow-double-submission)').preventDoubleSubmission();

By utilizing these techniques, you can prevent double form submissions and ensure smooth server processing.

The above is the detailed content of How to Prevent Double Form Submission in jQuery?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn