Home > Web Front-end > JS Tutorial > body text

How to Prevent Forms from Double Submission in jQuery with a Plugin?

Linda Hamilton
Release: 2024-11-10 20:57:03
Original
573 people have browsed it

How to Prevent Forms from Double Submission in jQuery with a Plugin?

How to Prevent Form Double Submission in jQuery with a Plugin

Preventing form resubmission is crucial when processing takes time on the server side. Unfortunately, disabling all form inputs, as you attempted with jQuery, can hinder form submission in some browsers.

Recommended Method: jQuery Plugin

To prevent double submission effectively, we recommend a custom jQuery plugin:

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:

Implement the plugin by selecting the form and invoking preventDoubleSubmission():

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

Customization:

If certain forms should allow multiple submissions per page load, assign them a class and exclude them from the selector:

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

Additional Considerations:

  • As mentioned in the original answer, ensuring operations are idempotent is an optimal solution.
  • This plugin relies on jQuery's data() method, which may not be supported by older browsers. Consider cross-browser compatibility before implementation.

The above is the detailed content of How to Prevent Forms from Double Submission in jQuery with a Plugin?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template