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>

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

// Disable the button
btn.disabled = true;

// Enable the button
btn.disabled = false;
</script>

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.


Comments

No comments yet...

Add comment

Subscribe to my newsletter