How to Check if a Checkbox is Checked in JavaScript
When building an HTML form containing checkboxes we may want to validate whether they have been checked using JavaScript before the form is allowed to submit.
In this tutorial, we will learn how to check if an HTML input
checkbox element is checked in JavaScript.
Check if .foo:checked is null
Let's say we had the following HTML checkbox input
with the class of .foo
.
<input type="checkbox" class="foo" name="ok">
We can check if it is checked by looking for .foo:checked
using the document.querySelector()
method. If a checkbox is not checked null will be returned.
if (result) {
console.log('Is checked')
} else {
console.log('Is NOT checked')
}
Is checked
Using the .checked Method
A cleaner way to achieve the same result as above is to use the built-in JavaScript .checked
method. It will return true
if the element is checked or false
if it is not.
result = document.querySelector('.foo').checked
if (result) {
console.log(result)
} else {
console.log(result)
}
true
Conclusion
You now know two different ways to find out if a checkbox is checked using JavaScript. You will notice that we never tried to get the value
of the checkbox input
. This is because it will always indicate that it is "on"
regardless of whether is it checked or not.