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

How to Prevent Double Form Submission in jQuery?

DDD
Release: 2024-11-10 08:14:02
Original
773 people have browsed it

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);
Copy after login

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;
};
Copy after login

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

$('form').preventDoubleSubmission();
Copy after login

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();
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template