Sometimes, we want to disable an HTML button using JavaScript.
In this article, we’ll look at how to disable an HTML button using JavaScript.
Setting the disabled Property of a Button to true
To disable an HTML button using JavaScript, we can select the button and then set the disabled
property of it.
For instance, if we have the following HTML:
<button>
click me
</button>
Then we can select the button with document.querySelector
and set its disabled
property by writing:
document.querySelector("button").disabled = true;
Now we should see the button is disabled.
Use the setAttribute Method to set the disabled Attribute of a Button
Another way to set the disabled
attribute of the button is to use the setAttribute
method.
For instance, if we have the following HTML:
<button>
click me
</button>
Then we can select the button with document.querySelector
and set its disabled
attribute with setAttribute
by writing:
document.querySelector("button").setAttribute("disabled", "disabled");
We call setAttribute
with the attribute name to set and the value to set it to as arguments respectively.
Also, we can write:
document.querySelector("button").setAttribute("disabled", true);
to set the disabled
attribute top true
to disable the button.
Conclusion
We can disable an HTML button with JavaScript by setting the disabled
attribute of the selected button with JavaSceipt.