Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all checked checkboxes

I have a set of input checkboxes with the same name and I would like to 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'); 
like image 653
Sameh Farahat Avatar asked Dec 19 '11 15:12

Sameh Farahat


People also ask

How do you check if all the checkboxes are checked in Javascript?

type == 'checkbox' && inputs[x]. name == 'us') { is_checked = inputs[x]. checked; if(is_checked) break; } } // is_checked will be boolean 'true' if any are checked at this point.


2 Answers

In IE9+, Chrome or Firefox you can do:

var checkedBoxes = document.querySelectorAll('input[name=mycheckboxes]:checked'); 
like image 142
PhilT Avatar answered Sep 21 '22 12:09

PhilT


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"); 
like image 45
Michael Berkowski Avatar answered Sep 25 '22 12:09

Michael Berkowski