Disable HTML button after clicking on it in JavaScript

In some situation, we may have to prevent a button from clicking on it on a web page. For example, on a registration form if we allow clicking multiple time before loading the other page we want to show after registration then it will not be right. It may create multiple accounts or may say validation error as it will use an email or password that already exists after a user clicked on the button first time.

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 clicking on a button.

For this, let’s create our button:

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

Now the button can be clicked multiple time. But we must have to prevent the button and we don’t want users to click on it multiple time.

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

   document.getElementById("btn").addEventListener("click", function(){ 
              // 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, 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 button by taking its ID and set the disabled property to true.

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 *