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!