How to disable a button using JavaScript

By

Learn how to disable or enable a button with JavaScript by selecting the element and setting its disabled property to true or false, useful for gating forms.

~~~

To disable a button using JavaScript, you select the element and set its disabled property to true. Set it back to false to enable it again.

An HTML button is one of the few elements that has its own state. Along with almost all the form controls.

One common thing that’s needed is to disable / enable the button programmatically using JavaScript.

For example you want to only enable the button when a text input element is filled.

Or when a specific checkbox is clicked, like the ones you see to say “I read the terms and conditions”, something that no one actually reads.

Here’s how to do it.

You select the element, using document.querySelector() or document.getElementById():

const button = document.querySelector('button')

If you have multiple buttons you might want to use document.querySelectorAll() and loop through the results.

Anyway, once you have the element reference, you set its disabled property to true to disable it:

button.disabled = true

To enable it back again, you set it to false:

button.disabled = false

A disabled button ignores clicks, can’t be focused, and won’t submit its form. The browser handles all of that for you.

A practical example

Let’s wire this up to a text input. The button starts disabled in the HTML, and we enable it only when the input has some text:

<input type="text" id="username" />
<button id="signup" disabled>Sign up</button>
const input = document.querySelector('#username')
const button = document.querySelector('#signup')

input.addEventListener('input', () => {
  button.disabled = input.value.trim() === ''
})

Every time the user types, we check the input. Empty input, disabled button. Some text, enabled button.

Notice the trim() call. Without it, a value made of spaces would count as filled, and the button would enable itself for no good reason.

How to style a disabled button

Browsers gray out disabled buttons a bit, but you usually want to make the state more obvious. Use the :disabled CSS selector:

button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

No JavaScript needed for the styling. The selector reacts to the property automatically.

A pitfall to avoid

Be careful if you use setAttribute() instead of the property. This does not enable the button:

button.setAttribute('disabled', 'false')

disabled is a boolean attribute. Its presence is what counts, not its value, so disabled="false" still means disabled.

If you work with the attribute, you have to remove it with button.removeAttribute('disabled'). My advice is to skip the problem entirely and always use the disabled property, as we did above. Assigning true or false to it always does what you expect.

~~~

Related posts about platform: