JQuery: Disable button after click event.

This is a short guide on how to disable a button with JQuery after it has been clicked. This kind of operation can come in handy if you want to make sure that a button is only clicked once; or if you want to disable a button while an Ajax request is being carried out.

Lets take a look at the following example code:

<!DOCTYPE html>
        <title>Disable Button - JQuery Example</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
        <p>Click the button below to disable it!</p>
        <button id="my_button">Click Here</button>
            $('#my_button').on('click', function(){
                alert('Button clicked. Disabling...');
                $('#my_button').attr("disabled", true);

In the example HTML above, we:

  1. Included the JQuery JavaScript library from the JQuery CDN.
  2. We created a simple button with the ID “my_button”.
  3. In the JavaScript at the end of the page, we added a JQuery “click” event handler to our “my_button” button.
  4. When the click event occurs, our handler function is executed. Inside this event handler function, we alert the user that the button has been pressed. Directly afterwards, we disable the button in question by using the JQuery attr method (we set the disabled attribute to “true”).

Once you’ve clicked on the button, you will find that you won’t be able to click on it again until you have refreshed the page. You will also notice that its appearance has become somewhat faded.