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:
<title>Disable Button - JQuery Example</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<p>Click the button below to disable it!</p>
<button id="my_button">Click Here</button>
alert('Button clicked. Disabling...');
In the example HTML above, we:
- We created a simple button with the ID “my_button”.
- 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.