In this article we will learn how to check if checkbox is checked or not.
It is very common to check if checkbox is checked or not in JavaScript.
Problem
Now we have a common problem, sometimes you have to find out if the check box is checked or not.
Imagine with me that you have a checkbox like this:
<input type="checkbox" id="checkbox">
We want to know whether it is checked or not using JavaScript.
How to solve this problem
We can solve this problem using checked
property.
Solution:
As we said before, the solution to this problem is easy, which is that we have to use the checked
property.
NOTE: checked
property returns true or false.
// Select element
const checkbox = document.querySelector('#checkbox');
// Print `checked` property
console.log(checkbox.checked);
Output
false
Change value of checked property
It is also possible to change the value of that property.
// Select element
const checkbox = document.querySelector('#checkbox');
// Change value to `true`
checkbox.checked = true;
// Result:
console.log(checkbox.checked);
// Change value to `false`
checkbox.checked = false;
// Result:
console.log(checkbox.checked);
Output
true
false
The Document method querySelector() returns the first Element within the document that matches the specified selector, or group of selectors. If no matches are found, null is returned. (Source: MDN)
Thank you for reading
Thank you for reading my blog. 🚀