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');
Code language: JavaScript (javascript)

Option 2 – Another one liner

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

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; }
Code language: JavaScript (javascript)

Now you simply call the function:

var checkedBoxes = getCheckedBoxes("mycheckboxes");
Code language: JavaScript (javascript)

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments