Home » Html » How to get all checked checkboxes

How to get all checked checkboxes

Posted by: admin November 29, 2017 Leave a comment

Questions:

I have a set of input checkboxes with same name
and I would like 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');
Answers:

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");

Questions:
Answers:

In IE9+, Chrome or Firefox you can do:

var checkedBoxes = document.querySelectorAll('input[name=mycheckboxes]:checked');