Disable a HTML Button in JavaScript [With Examples]

Alvaro Trigo Avatar

Follow on Twitter

To disable a button using only JavaScript you need to set the disabled property to true. 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 using JavaScript
document.querySelector('#button').disabled = true;
Code language: JavaScript (javascript)
// Enabling a disabled button to enable it again 
document.querySelector('#button').disabled = false;
Code language: JavaScript (javascript)

These are the steps we have to follow:

  1. Select the button element you want to disable.
  2. Set the disabled property to false.

The disabled property reflects the HTML attribute disabled 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);
Code language: JavaScript (javascript)

Here’s the codepen so you can test it out yourself and play a bit more with it by changing the code:

If you are using jQuery, check out our article on how to disable a button using jQuery. The process is pretty similar.


Was this page helpful?