How to get all checked checkboxes in Javascript

0 min read 88 words

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

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags