How to disable button in JavaScript

Disable a button using JavaScript

Posted by Ervin Adams on August 11, 2022

How to disable button in JavaScript

Disable a button using JavaScript

Posted by Ervin Adams on August 11, 2022

To disable button using JavaScript:

Step 1. Add onClick attribute with disBtn() function to button

Step 2. Get the specified button using document.getElementById()

Step 3. Set disabled attribute to button

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>wecode101 disable button using JavaScript</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>
<body>
    <div class="container">
        <div class="col-9 pt-5 mx-auto">
            <button type="button" class="btn btn-primary" onClick='disBtn()' id="s-btn">Submit</div>
        </div>
    </div>
</body>
</html>

JS

Let's look at a couple of ways to disable a button based on the steps above:

Option 1. Set disabled attribute to true on document.getElementById()

function disBtn(){
  document.getElementById("s-btn").disabled = true;
}

Option 2. Set disable attribute using setAttribute() method

function disBtn(){
  document.getElementById("s-btn").setAttribute('disabled', 'disabled');
}

To remove the disable attribute, set disabled attribute to false on document.getElementById():

document.getElementById("s-btn").disabled = false;