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.
To start, let's use the following checkbox in our HTML:
<input type="checkbox" class="checkbox" />
const checkbox = document.querySelector(".checkbox");
From there, we can check the state of the checkbox. To do this, use the
const checkbox = document.querySelector(".checkbox"); const isChecked = checkbox.checked;
Alternatively, you can use the
:checked CSS selector:
const 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.
As mentioned before, this is a common requirement as checkboxes are so common on the web.
Hopefully, this post has helped you! Happy coding!
Leave us a message!