How to prevent the form from submitting multiple times from the client side with JavaScript?

Estimated read time 2 min read

To prevent a form from submitting multiple times from the client side with JavaScript, you can disable the form’s submit button after it has been clicked once. Here is an example of how to do this:


<form id="myForm" action="submit.php" method="post">
  <!-- form fields go here -->
  <button type="submit" id="submitBtn">Submit</button>


const form = document.getElementById('myForm');
const submitBtn = document.getElementById('submitBtn');

form.addEventListener('submit', (event) => {
  event.preventDefault(); // prevent the form from submitting

  // disable the submit button
  submitBtn.disabled = true;

  // submit the form after a short delay
  setTimeout(() => {
  }, 500);

In this code, we add an event listener to the form’s submit event. When the form is submitted, we prevent the default form submission behavior using event.preventDefault(). We then disable the submit button using submitBtn.disabled = true.

To submit the form, we use a setTimeout function with a delay of 500 milliseconds (0.5 seconds). This delay gives the user enough time to see that the button has been disabled and to prevent them from clicking the button multiple times in quick succession. After the delay, we submit the form using form.submit().

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply