How to Check if Checkbox is Checked using JavaScript
Table of Contents
Forms are an important part of the modern web, and that includes the use of checkboxes.
Checkboxes are used to allow the user to select and unselect an option, and are popular for things like license agreements and multi-select lists.
With that said, needing to know the state of the checkbox in JavaScript is a common requirement.
In this post, we'll learn how to check the state of a checkbox in JavaScript.
Check the state of a checkbox in JavaScript
To start, let's use the following checkbox in our HTML:
HTML<input type="checkbox" class="checkbox" />
First, we need to query for it in JavaScript.
JAVASCRIPTconst checkbox = document.querySelector(".checkbox");
From there, we can check the state of the checkbox. To do this, use the checked
property:
JAVASCRIPTconst checkbox = document.querySelector(".checkbox");
const isChecked = checkbox.checked;
Alternatively, you can use the :checked
CSS selector:
JAVASCRIPTconst isChecked = document.querySelector(".checkbox:checked") !== null;
This works because the browser will automatically add the :checked
selector to the element if it is checked, and so we can query for it.
Conclusion
In this post, we learned how to check the state of a checkbox in JavaScript.
As mentioned before, this is a common requirement as checkboxes are so common on the web.
Hopefully, this post has helped you! Happy coding!
- How to build a Discord bot using TypeScript
- How to deploy a PHP app using Docker
- Getting Started with Deno
- Learn how to use v-model with a custom Vue component
- Using Puppeteer and Jest for End-to-End Testing
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting User Location using JavaScript's Geolocation API
- Learn how to build a Slack Bot using Node.js
- Creating a Twitter bot with Node.js
- Using Push.js to Display Web Browser Notifications
- Building a Real-Time Note-Taking App with Vue and Firebase
- Getting Started with React