A checkbox can have only two states either checked or unchecked. When the checkbox is checked, the checked
attribute is set to true otherwise it is set to false.
We can take advantage of this concept and easily get the list of all checked checkboxes. Below are the steps that you can follow:
- Select all the checkboxes using any DOM method such as
querySelectorAll()
orgetElementsByClassName()
, etc. - Iterate over each checkbox and check if it is checked or not using the
checked
attribute. - If the value of the
checked
attribute is true, the checkbox is checked. Therefore, get its value using thecheckbox.value
attribute and add it to the selected list.
Here is a working example:
Example:
var checkboxes = document.querySelectorAll('input[type=checkbox]'); var selectedCheckboxes = []; function getSelectedValues(){ selectedCheckboxes = []; for(let i=0;i<checkboxes.length;i++){ if(checkboxes[i].checked){ selectedCheckboxes.push(checkboxes[i].value); } } if(selectedCheckboxes.length==0){ alert("You haven't selected any checkbox"); }else{ alert('You have selected: '+ selectedCheckboxes); } }
If you want to select the checkboxes by their class name, you can simply replace the querySelectorAll()
method with getElementsByClassName()
. The rest of the code will remain the same.
var checkboxes = document.getElementsByClassName('yourClass');