Use-Cases of this Tutorial
- Know how to check / uncheck a checkbox with Javascript.
- Know whether checkbox is checked.
- Know how to get values of selected checkboxes from a group.
This tutorial explains how to manipulate HTML checkboxes with Javascript. Most of the operations can be performed through the checked property of the checkbox DOM element.
Checking a Checkbox
To check a checkbox, the checked property of the DOM element can be set to true.
<input type="checkbox" id="will-attend" />
document.querySelector("#will-attend").checked = true;
Unchecking a Checkbox
The checked property of the checkbox DOM element can be set to false to uncheck it.
<input type="checkbox" id="will-attend" />
document.querySelector("#will-attend").checked = false;
Find whether a Checkbox is Checked or Unchecked
There are two ways in which it can be found whether a checkbox is checked or not :
-
The value of the checked property of the checkbox DOM element can be read. If true then it is checked, if false then unchecked.
<input type="checkbox" id="will-attend" />
var checked = document.querySelector("#will-attend").checked; if(checked) console.log('Checked'); else console.log('Unchecked');
-
The CSS pseudo-class :checked selector can be used to find whether the checked DOM elements exists or not.
<input type="checkbox" id="will-attend" />
// getting the checked DOM element var checked_element = document.querySelector("#will-attend:checked"); if(checked_element !== null) console.log('Checked'); else console.log('Unchecked');
Getting Value of a Checkbox
The value of the checkbox can be found with the value property.
<input type="checkbox" id="will-attend" value="1" />
var value = document.querySelector("#will-attend").value;
Handling Multiple Checkboxes
Assuming multiple checkboxes can be selected from a group, and we need to get all selected values :
<input type="checkbox" class="car" value="Ferrari" /><label>Ferrari</label>
<input type="checkbox" class="car" value="Mercedes" /><label>Mercedes</label>
<input type="checkbox" class="car" value="BMW" /><label>BMW</label>
// get all checked elements
var checked_elements = document.querySelectorAll(".car:checked");
var checked_elements_values = [];
// loop through all checked elements
checked_elements.forEach(function(element) {
checked_elements_values.push(element.value);
});
if(checked_elements_values.length == 0)
console.log('No items checked');
else
console.log(checked_elements_values);