Home > Web Front-end > JS Tutorial > How to Prevent Double Form Submissions in jQuery: What Techniques Work Best?

How to Prevent Double Form Submissions in jQuery: What Techniques Work Best?

DDD
Release: 2024-11-09 15:07:02
Original
202 people have browsed it

How to Prevent Double Form Submissions in jQuery: What Techniques Work Best?

How to Prevent Double Form Submissions in jQuery

When working with forms that take a significant amount of time to process, preventing users from accidentally submitting the form multiple times is crucial. This article discusses a method to achieve this using jQuery.

Initial Attempt

The initial approach involved disabling all inputs and buttons upon form submission. However, this technique resulted in the form not being submitted in Firefox.

Improved Solution

The solution lies in selectively disabling only the submit buttons, as disabling all inputs may interfere with form submission. The following jQuery code accomplishes this:

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

Alternative Plugin Approach

Another option is to use the jQuery plugin below, which utilizes jQuery's data() function to mark forms as submitted, preventing subsequent submissions.

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

    if ($form.data('submitted') === true) {
      e.preventDefault();
    } else {
      $form.data('submitted', true);
    }
  });

  return this;
};
Copy after login

Usage:

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

Excluding AJAX Forms

If your application has AJAX forms that should allow multiple submissions, you can exclude them by adding a class, as seen below:

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

The above is the detailed content of How to Prevent Double Form Submissions in jQuery: What Techniques Work Best?. 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