How to get all checked checkboxes
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");