15 1 0 4000 1 https://codeblock.co.za 300 true 0
theme-sticky-logo-alt
Prevent Multiple Form Submissions With JQuery or Vanilla JavaScript

Prevent Multiple Form Submissions With JQuery or Vanilla JavaScript

0 Comments

Have a form that sends data that takes more than a few seconds to process? Your user might think that nothing’s happened after they’ve clicked and end up sending multiple form submissions. Luckily, this can be prevented easily with JQuery and even vanilla JavaScript.

Prerequisites

  • Some understanding of JQuery (if you’re going to use this method).
  • Some understanding of JavaScript (if you’re going to use this method).

Use JQuery to Prevent Multiple Form Submissions

To prevent the user from submitting a form multiple times, we’ll use JQuery to listen for the submission event. Once the form is submitted, we’ll add a disabled attribute to the button to prevent multiple form submissions. Now the user can’t click it again. Changing the “Submit” text is optional, but it’s a great way to give your user feedback so they know that something is happening while they wait. As an example, a WooCommerce order created programmatically may take a few seconds to run so you wouldn’t want your customer to create duplicate orders. It would be an administrative nightmare.

$('#formID').submit(function(){

  // Disable the submit button      
  $('#submitID').attr('disabled', true);

  // Change the "Submit" text
  $('#submitID').prop('value', 'Please wait...');
  
  return true;
       
});

Prevent Multiple Form Submissions with Vanilla JavaScript

This short JavaScript snippet does exactly the same thing as the JQuery above with some changes in the syntax.

var form = document.getElementById('formID');
var submitButton = document.getElementById('submitID');

form.addEventListener('submit', function() {

   // Disable the submit button
   submitButton.setAttribute('disabled', 'disabled');

   // Change the "Submit" text
   submitButton.value = 'Please wait...';
			
}, false);

Which Method To Use

If your website or app is already using JQuery, then you can simply copy the code into your file that handles your JQuery scripts.

If you don’t use JQuery on your site, it would be unwise to install JQuery to handle just one script, so the pure JavaScript method would be your best option.

Where To Use This Code

Copy and paste the code into the .js file that handles your JavaScript OR paste it between <script> tags in the HTML/PHP file that has your form.

Is this still valid in 2024? Please let me know in the comments below.

Was This Helpful?

How to Validate a South African ID Number With PHP
Previous Post
How to Validate a South African ID Number With PHP
How to Create Pagination With PHP
Next Post
How to Create Pagination With PHP

0 Comments

Leave a Reply