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');
type == 'checkbox' && inputs[x]. name == 'us') { is_checked = inputs[x]. checked; if(is_checked) break; } } // is_checked will be boolean 'true' if any are checked at this point.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With