Skip to content

How to disable a button using JavaScript

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
→ Download my free JavaScript Handbook!

THE VALLEY OF CODE

THE WEB DEVELOPER's MANUAL

You might be interested in those things I do:

  • Learn to code in THE VALLEY OF CODE, your your web development manual
  • Find a ton of Web Development projects to learn modern tech stacks in practice in THE VALLEY OF CODE PRO
  • I wrote 16 books for beginner software developers, DOWNLOAD THEM NOW
  • Every year I organize a hands-on cohort course coding BOOTCAMP to teach you how to build a complex, modern Web Application in practice (next edition February-March-April-May 2024)
  • Learn how to start a solopreneur business on the Internet with SOLO LAB (next edition in 2024)
  • Find me on X

Related posts that talk about browser: