How to disable a button in JavaScript

Overview

JavaScript provides many methods to interact with the HTML DOM. We can use them to disable a button.

To disable a button in JavaScript, we get its reference and then set its disable property to true.

Syntax

document.getElementById("Provide id of the button").disabled = true;

Let's consider a coding example of this.

Code

A simple example of enabling and disabling a button in JavaScript

Explanation

In the code above, we created two buttons. We click the second button to disable or enable the first button, as follows:

  • Lines 1–2: We get the references of both buttons and assign them to the btn1 and btn2 variables, respectively.
  • Line 4: We initialize the isDisabled variable that stores the state of the button to be disabled or enabled.
  • Line 6: We add a click event listener on the second button. Whenever we click the second button, the first button is enabled or disabled.

Free Resources