How to disable a button in JavaScript
Overview
JavaScript provides many methods to interact with the HTML DOM. We can use them to disable a button.
To disable a button in JavaScript, we get its reference and then set its disable property to true.
Syntax
document.getElementById("Provide id of the button").disabled = true;
Let's consider a coding example of this.
Code
Explanation
In the code above, we created two buttons. We click the second button to disable or enable the first button, as follows:
- Lines 1–2: We get the references of both buttons and assign them to the
btn1andbtn2variables, respectively. - Line 4: We initialize the
isDisabledvariable that stores the state of the button to be disabled or enabled. - Line 6: We add a click event listener on the second button. Whenever we click the second button, the first button is enabled or disabled.