How to disable a button in jquery

Disable a button using jquery

Posted by Luke Beeno on August 10, 2022

How to disable a button in jquery

Disable a button using jquery

Posted by Luke Beeno on August 10, 2022

To disable button using Jquery:

Step 1. Get the specified botton field by using selector $("#id")

Step 2. Add an onclick event listener to the button

Step 3. Set disabled attribute to button

Here is the HTML that will be used for the example:

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>wecode101 disable button using jquery</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">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
    <div class="container">
        <div class="col-9 pt-5 mx-auto">
            <button type="button" class="btn btn-primary" 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 disable attribute using attr() method

$( "#s-btn" ).click(function(){
    $("#s-btn").attr("disabled", true);
});

Option 2. Set disable attribute using prop() method

$( "#s-btn" ).click(function(){
    $("#s-btn").prop("disabled", true);
});

To remove the disable attribute use removeAttr() method:

$('#s-btn').removeAttr('disabled');