javascript

How to Disable Button in Javascript


In this article, you will learn how to disable a button in Javascript.

Let’s say you have a button element with id “theButton”.

html

<button id="theButton">Hi, I'm a button</button>

In order to disable the button, you can use the document.getElementById() method and button disabled property, button.disabled.

full html

<!-- A button element with id "theButton" -->
<button id="theButton">Hi, I'm a button</button>

<!-- A button element that executes "disableButton" function upon clicking -->
<button onclick="disableButton()">Disable</button>

full javascript

// A function that disables button
function disableButton() {
  // Select the element with id "theButton" and disable it
  document.getElementById("theButton").disabled = true;
}

Before disabling button

After disabling button

Note: The document.getElementById() method functions by getting an element whose id matches the supplied string. The button disabled property, button.disabled functions by preventing the user from interacting with the button.


Share on social media

//