How to Disable a Button Using JavaScript

The HTML button element can be disabled dynamically by applying an attribute to it using JavaScript. This can be useful in scenarios where a user should not be able to submit a form before certain fields are filled or to stop users from accidentally submitting an ajax form twice.

 

Here we will look at how to disable a button using JavaScript, from the most basic way to a more comprehensive “real-world” solution for a form.

 

The most basic way is to use the JavaScript document.querySelector utility to find an HTML button element and add a disabled attribute to it.

 

document.querySelector("button").disabled = true;

 

This is a nice one-line solution however if there are multiple buttons on the page it might not deliver the behaviour we want. On top of that if we want to enable the button again we would have to write the entire querySelector utility again, unnecessarily bloating the code.

 

A more robust solution would be to put an id attribute on the HTML button element that should be disabled, select it using the getElementById utility and store the element in a constant.

 

<button id="send">Send</button>
const button = document.getElementById("send");

 

Now we can easily enable or disable the button like this:

 

button.disabled = true;
button.disabled = false;

 

Conclusion

You now know how to disable and enable an HTML button using JavaScript.