How to Disable a Button using JavaScript
Table of Contents
A common task in web development is how to programmatically disable a button using JavaScript.
In this post, we'll learn how you can use JavaScript to disable a button.
An example of when you'd want to do this is when you want to prevent a user from submitting a form until all the required fields are filled out.
A button has an internal state, similar to checkboxes and radio buttons.
This means we can manipulate the state of the button, and therefore disable it.
How to disable a button
The first thing you'll want to do is to get the button element.
If you have a class applied, you can get your button like this:
JAVASCRIPTconst button = document.querySelector(".button");
Now that you've gotten your button, simply set its disabled
property to true
.
JAVASCRIPTconst button = document.querySelector(".button");
button.disabled = true;
Conclusion
In this post, we've seen how to get a button and then disable it programmatically using JavaScript.
Hopefully, this has been helpful to you.
Happy coding!
- How to Install Node on Windows, macOS and Linux
- Getting Started with Solid
- How to Set Up Cron Jobs in Linux
- How to deploy a PHP app using Docker
- How to deploy a Deno app using Docker
- Getting Started with Deno
- How to deploy an Express app using Docker
- Getting Started with Handlebars.js
- Learn how to build a Slack Bot using Node.js
- Using Push.js to Display Web Browser Notifications
- Building a Real-Time Note-Taking App with Vue and Firebase
- Setting Up a Local Web Server using Node.js