How to get all checked checkboxes
I have a set of input checkboxes with the same name and I would like to determine which checkboxes have been checked using javascript, how can I achieve that? I know only how to get all the checkboxes as follows:
var checkboxes = document.getElementsByName('mycheckboxes');
In IE9+, Chrome or Firefox you can do:
var checkedBoxes = document.querySelectorAll('input[name=mycheckboxes]:checked');
A simple for loop which tests the checked
property and appends the checked ones to a separate array. From there, you can process the array of checkboxesChecked
further if needed.
// Pass the checkbox name to the function
function getCheckedBoxes(chkboxName) {
var checkboxes = document.getElementsByName(chkboxName);
var checkboxesChecked = [];
// loop over them all
for (var i=0; i<checkboxes.length; i++) {
// And stick the checked ones onto an array...
if (checkboxes[i].checked) {
checkboxesChecked.push(checkboxes[i]);
}
}
// Return the array if it is non-empty, or null
return checkboxesChecked.length > 0 ? checkboxesChecked : null;
}
// Call as
var checkedBoxes = getCheckedBoxes("mycheckboxes");
For a simple two- (or one) liner this code can be:
checkboxes = document.getElementsByName("NameOfCheckboxes");
selectedCboxes = Array.prototype.slice.call(checkboxes).filter(ch => ch.checked==true);
Here the Array.prototype.slice.call()
part converts the object NodeList of all the checkboxes holding that name ("NameOfCheckboxes") into a new array, on which you then use the filter method. You can then also, for example, extract the values of the checkboxes by adding a .map(ch => ch.value)
on the end of line 2.
The => is javascript's arrow function notation.
Get all the checked checkbox value in an array - one liner
const data = [...document.querySelectorAll('.inp:checked')].map(e => e.value);
console.log(data);
<div class="row">
<input class="custom-control-input inp"type="checkbox" id="inlineCheckbox1" Checked value="option1">
<label class="custom-control-label" for="inlineCheckbox1">Option1</label>
<input class="custom-control-input inp" type="checkbox" id="inlineCheckbox1" value="option2">
<label class="custom-control-label" for="inlineCheckbox1">Option2</label>
<input class="custom-control-input inp" Checked type="checkbox" id="inlineCheckbox1" value="option3">
<label class="custom-control-label" for="inlineCheckbox1">Option3</label>
</div>