How to Get All Checked Checkbox Values in JavaScript?

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:

  1. Select all the checkboxes using any DOM method such as querySelectorAll() or getElementsByClassName(), etc.
  2. Iterate over each checkbox and check if it is checked or not using the checked attribute.
  3. If the value of the checked attribute is true, the checkbox is checked. Therefore, get its value using the checkbox.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');

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.