Disable a Button With JavaScript [With Examples]
To disable a button using only JavaScript you need to set its disabled
property to false
. For example: element.disabled = true
.
And to enable a button we would do the opposite by setting the disabled
JavaScript property to false
.
Here a more complete example where we select the button and then we change its disabled property:
// Disabling a button
document.querySelector('#button').disabled = true;
// Enabling a disabled button to enable it again
document.querySelector('#button').disabled = false;
These are the steps we have to follow:
- Query the button you want to disable
- Set the
disabled
property tofalse
.
The
disabled
property reflects the HTML attributedisabled
and provide a way to change this property dynamically with JavaScript.
Disable button example
For demo purposes and to keep it as simple as possible we'll be disabling the button when clicking on itself:
const button = document.querySelector('#button');
const disableButton = () => {
button.disabled = true;
};
button.addEventListener('click', disableButton);
Here's the codepen so you can test it out yourself and play a bit more with it by changing the code:
References
Related articles
- Disable a button with jQuery
- JavaScript Alert (Examples and Usage)
- The Best Way to Learn JavaScript
- How long does it take to learn JavaScript?
Join 2,000+ readers and learn something new every month!