Sunday, March 19, 2023
HomeSoftware EngineeringThe best way to get all checked checkboxes in Javascript

The best way to get all checked checkboxes in Javascript


If it is advisable get all of the checked checkboxes utilizing Javascript, then you are able to do the next:

Choice 1 – In a single line

const checkedBoxes = doc.querySelectorAll('enter[name=mycheckboxes]:checked');

Choice 2 – One other one liner

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

Choice 3 – Create a helper perform

perform getCheckedBoxes(checkboxName) {
  var checkboxes = doc.getElementsByName(checkboxName);
  var checkboxesChecked = [];

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

Now you merely name the perform:

var checkedBoxes = getCheckedBoxes("mycheckboxes");
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments