How to Get All Checked Checkboxes in Javascript


If you need to get all the checked checkboxes using Javascript, then you can do the following:

Option 1 – In a single line

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

Option 2 – Another one liner

const data = [...document.querySelectorAll('.mycheckboxes:checked')].map(e => e.value);

Option 3 – Create a helper function

function getCheckedBoxes(checkboxName) {
  var checkboxes = document.getElementsByName(checkboxName);
  var checkboxesChecked = [];

  for (var i=0; i<checkboxes.length; i++) {
     if (checkboxes[i].checked) checkboxesChecked.push(checkboxes[i]);
     }
  }
  return checkboxesChecked.length > 0 ? checkboxesChecked : null;
}

Now you simply call the function:

var checkedBoxes = getCheckedBoxes("mycheckboxes");