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:

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.

Comments

comments