How to disable a button - JavaScript

/ #JavaScript

Let me show you how to use JavaScript to programmatically disable or enable a button.

There aren't many HTML elements who has their own state, but the button actually has. A typical task you use JavaScript for in a form, is to enable or disable a button based on the validation or something similar.

A quick example

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

// Button
const btn = document.getElementById('btn');

// Disable the button
btn.disabled = true;

// Enable the button
btn.disabled = false;

If you add this code to a file and open it in a browser, the button will work as expected since we first disabled it and then enabled it again. Try to remove the line where we set the disabled state to false and try again. This time, the button will not work.


No comments yet...

Add comment


Please log in to comment!


Subscribe to my weekly newsletter. One time per week I will send you a short summary of the tutorials I have posted in the past week.