How to Prevent Double Form Submission in JavaScript



In this article, you will learn how to prevent double form submission in JavaScript.

Preventing double form submission in JavaScript

Preventing double form submission is an important aspect of web development to avoid data duplication and improve user experience. In JavaScript, this can be achieved by disabling the submit button after it is clicked and re-enabling it once the form submission is completed.

Here are the steps to prevent double form submission in JavaScript:

Attach an event listener to the form submission event:

const form = document.querySelector('#myForm');
form.addEventListener('submit', (event) => {
  // Prevent default form submission

  // Disable submit button to prevent double submission
  const submitBtn = document.querySelector('#submitBtn');
  submitBtn.disabled = true;

  // Submit form data

Inside the event listener, disable the submit button using the disabled attribute.

Submit the form data using an AJAX request or by redirecting to another page.

After the form submission is completed, re-enable the submit button:

function submitFormData() {
  // Perform form submission
  // ...

  // Re-enable submit button
  const submitBtn = document.querySelector('#submitBtn');
  submitBtn.disabled = false;

Here’s an example HTML form with a submit button:

<form id="myForm">
  <label for="name">Name:</label>
  <input type="text" id="name" name="name"><br><br>
  <label for="email">Email:</label>
  <input type="email" id="email" name="email"><br><br>
  <button type="submit" id="submitBtn">Submit</button>

In the above example, the form submission is prevented using the event.preventDefault() method, and the submit button is disabled using the submitBtn.disabled = true statement. After the form data is submitted, the submitBtn.disabled = false statement re-enables the submit button.