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
DDDOriginal
2024-11-09 15:07:02242browse

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

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

Usage:

$('form').preventDoubleSubmission();

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

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!

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