Disable HTML button after the first click on it in JavaScript

There are situations when you need to prevent a button from clicking on it on a web page after the first click. For example, on a registration form if we allow clicking multiple times to the HTML button before loading the other page we want to show after registration then it may create problems. We may not perform the same task to be performed when the button clicked a second time or so on.

Run JavaScript code or call a function after n seconds

Now here in this post, we are going to see a simple example where we will disable click after the first click on the button.

For this, let’s create our button:

<button id="btn">Click Me</button>

Now the button can be clicked multiple times. But we must have to prevent the button from clicking multiple times. Only the first click will performed.

We can easily prevent users from clicking the button. Below is our JavaScript code that will do that:

document.getElementById("btn").addEventListener("click", function(){
         console.log("It works");
        // Preventing button from clicking
        document.getElementById("btn").disabled = true;
});

 

Get the scroll position of a web page in the browser window using JavaScript

Locate the Geo-position of a visitor in JavaScript

In the above JavaScript code, we have used the click event listener to detect the click on the button. When someone clicks the button using the mouse or touchpad, then the code inside the event listener will work where we have placed the code that will prevent clicking on the button. We are getting the button by taking its ID and set the disabled property to true.

To be confirmed, we are printing the text “It works” in the console. It should be printed in the console only once after clicking our button the first time.


That’s it. We did it. We have successfully prevented our button from clicking multiple times.

Leave a Reply

Your email address will not be published. Required fields are marked *