Home  >  Article  >  Web Front-end  >  How to Prevent Forms from Double Submission in jQuery with a Plugin?

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

Linda Hamilton
Linda HamiltonOriginal
2024-11-10 20:57:03574browse

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

Usage:

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

$('form').preventDoubleSubmission();

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

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!

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