
Apu
January 19, 2024 ›
#HowTo
›
#Javascript
❌
Simplest way to disable button on submission of a form using JavaScript?
I need some help with a JavaScript problem. So, here's the situation:
I have a form in my web application, and I want to disable a specific button on submission of the form. Basically, after the user clicks the submit button, I don't want them to be able to click it again until the form processing is complete. I'm sure it's a common issue, but I can't seem to find a straightforward solution.
And here's what I've tried so far (but it's not working).
save
listen
AI Answer
Simplest way to disable button on submission of a form using JavaScript?
4
I need some help with a JavaScript problem. So, here's the situation: I have a form in…
asked
Apu
4 answers
2915
I need some help with a JavaScript problem. So, here's the situation: I have a form in…
Answer Link
answered
Apu
document.getElementById("myForm").addEventListener("submit", function(event) {
event.preventDefault();
document.getElementById("submitButton").disabled = true;
});
But hey, what if I want to re-enable the button after the form processing is done? Any ideas on how to achieve that?
document.getElementById("myForm").addEventListener("submit", function(event) {
event.preventDefault();
var submitButton = document.getElementById("submitButton");
submitButton.disabled = true;
setTimeout(function() {
submitButton.disabled = false;
alert("Form processing is complete!");
}, 3000);
});
In this example, I'm using a simple setTimeout() function to simulate the form processing that takes 3 seconds. Once the processing is complete, the button will be re-enabled, and an alert will notify the user that the processing is done. You can replace the setTimeout with your actual asynchronous process, like an AJAX call to the server, for instance.
document.getElementById("myForm").addEventListener("submit", function(event) {
event.preventDefault();
var submitButton = document.getElementById("submitButton");
if (!submitButton.disabled) {
submitButton.disabled = true;
setTimeout(function() {
submitButton.disabled = false;
alert("Form processing is complete!");
}, 3000);
}
});
This way, we prevent multiple form submissions and ensure a smooth user experience.