In this article we will learn how to check if checkbox is checked or not.
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">
How to solve this problem
We can solve this problem using
As we said before, the solution to this problem is easy, which is that we have to use the
checked property returns true or false.
// Select element const checkbox = document.querySelector('#checkbox'); // Print `checked` property console.log(checkbox.checked);
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);
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. 🚀