Sometimes, we want to prevent form from submitting multiple times from client side with JavaScript.
In this article, we’ll look at how to prevent form from submitting multiple times from client side with JavaScript.
How to prevent form from submitting multiple times from client side with JavaScript?
To prevent form from submitting multiple times from client side with JavaScript, we can disable the button when the form is being submitted.
For instance, we write
<form method="POST" action="...">
...
<input type="submit" name="myButton" value="Submit" />
</form>
to add a form element.
Then we add
const checkForm = (e) => {
e.preventDefault();
e.target.myButton.disabled = true;
e.target.myButton.value = "Please wait...";
};
const form = document.querySelector("form");
form.onsubmit = checkForm;
to select the form with querySelector.
Then we set the onsubmit property of the form to the checkForm function.
In it, we call preventDefault to stop the default server side form submission behavior.
Then disable the submit button with
e.target.myButton.disabled = true;
Next, we set the button’s text with
e.target.myButton.value = "Please wait...";
Conclusion
To prevent form from submitting multiple times from client side with JavaScript, we can disable the button when the form is being submitted.