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> <html> <head> <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> </head> <body> <p>Click the button below to disable it!</p> <button id="my_button">Click Here</button> <script> $('#my_button').on('click', function(){ alert('Button clicked. Disabling...'); $('#my_button').attr("disabled", true); }); </script> </body> </html>
In the example HTML above, we:
- Included the JQuery JavaScript library from the JQuery CDN.
- We created a simple button with the ID “my_button”.
- In the JavaScript at the end of the page, we added a JQuery “click” event handler to our “my_button” 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.