Checking if a checkbox is checked
To get the state of a checkbox, whether checked or unchecked, you follow these steps:
- First, select the checkbox using the selecting DOM methods such as
- Then, access the
checkedproperty of the checkbox element. If its
true, then the checkbox is checked; otherwise, it is not.
Suppose that you have a checkbox like this:
To check if the
accept checkbox is checked, you use the following code:
Additionally, you can use use the
querySelector() to check if the
:checked selector does not return
null, like this:
If a checkbox does not have the
value attribute, its default value is
If you get the
value attribute of a checkbox, you always get the
'on' string whether the checkbox is checked or not. For example:
See the following example:
Getting values of multiple selected checkboxes
Assuming that you have three checkboxes and you want to get values of all the selected checkboxes:
To accomplish this, you need to add two more HTML attributes to each checkbox:
value . All three checkboxes need to have the same name but distinct values, for example:
To select the selected checkboxes, you use the
And gather the value of each checkbox:
Put it all together:
Check / Uncheck all checkboxes
Sometimes, you may want to check and uncheck all checkboxes on a form. See the following example:
When you click the button with the id
btn, all the checkboxes will be checked if they are not, and unchecked if they are already checked.
First, develop a
check() function that checks or unchecks all checkboxes based on an input argument:
When you click the button, you can call the
check() function to select all checkboxes. Next time, when you click the button, it should uncheck all the checkboxes.
To do this switch, you need to reassign the click event handler whenever the click event fires.
The following select the button and attach a click event listener:
checkAll() function is as follows:
uncheckAll() function is:
How it works:
If you click the button, the
uncheck() function is invoked to check all checkboxes. Then, it reassigns the
uncheckAll() function to the
onclick event handler.
Next time, if you click the button, the
uncheckAll() function is invoked to uncheck all the checkboxes and reassign the
checkAll() function to the
onclick event handler.
- Do use
:checkselector to determine if a checkbox is checked.
- Query the
valueattribute to get the value of a checkbox.