Skip to content

How to disable a button using JavaScript

New Course Coming Soon:

Get Really Good at Git

Find out how to programmatically disable or enable a button using JavaScript

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 to enable it again:

button.disabled = false
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching Summer 2024. Join the waiting list!
→ Read my DOM Tutorial on The Valley of Code
→ Read my Browser Events Tutorial on The Valley of Code
→ Read my Browser APIs Tutorials on The Valley of Code

Here is how can I help you: