Anjan Dutta

How to disable a button using JavaScript

How to disable a button using JavaScript

We can disable a button using the setAttribute property in JavaScript.

Take a look at the working code below.

The HTML

<html>
<head>
<title></title>
</head>
<body>
<form name="myForm">
<button id="btn" onclick="disableMe()">Click to Disable!</button>
</form>
<p>
<p>
Checkout my <a href="https://anjandutta.com">blog</a> for more tutorial.
</body>
</html>

The JavaScript

function disableMe() {
document.getElementById("btn").setAttribute("disabled", "true");
}

In the above code, we are accessing the button by it's ID and setting the disabled attribute to true on click of the button.