/

How to Disable a Button Using JavaScript

How to Disable a Button Using JavaScript

Learn 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. There are many scenarios where it is necessary to disable or enable a button using JavaScript.

For instance, you may want to enable the button only when a text input element is filled, or when a specific checkbox is clicked (e.g., the checkboxes that are used to indicate acceptance of terms and conditions).

Here is how you can achieve this functionality:

First, select the button element using either document.querySelector() or document.getElementById():

1
const button = document.querySelector('button');

If you have multiple buttons, you can use document.querySelectorAll() and loop through the results.

Once you have the reference to the button element, you can disable it by setting its disabled property to true:

1
button.disabled = true;

To enable the button again, you simply set the disabled property to false:

1
button.disabled = false;

By following these steps, you can easily disable or enable a button using JavaScript in various scenarios.

tags: [“JavaScript”, “button”, “disable”, “enable”, “programming”]