R J
R J

Reputation: 505

How to check one check box if other check boxes checked using javascript?

var select_all = document.getElementById("select_all"); //select all checkbox
var checkboxes = document.getElementsByName("testc"); //checkbox items

//select all checkboxes
select_all.addEventListener("change", function(e) {
  for (i = 0; i < checkboxes.length; i++) {
    checkboxes[i].checked = select_all.checked;
  }
});


for (var i = 0; i < checkboxes.length; i++) {
  checkboxes[i].addEventListener('change', function(e) { //".checkbox" change
    //uncheck "select all", if one of the listed checkbox item is unchecked
    if (this.checked == false) {
      select_all.checked = false;
    }
    //check "select all" if all checkbox items are checked
    if (document.querySelectorAll('.checkbox:checked').length == checkboxes.length) {
      select_all.checked = true;
    }
  });
}
<li><input type="checkbox" id="select_all" /> Selecct All</li>
<ul>
  <li><input class="checkbox" type="checkbox" name="testc"> This is Item 1</li>
  <li><input class="checkbox" type="checkbox" name="testc"> This is Item 2</li>
  <li><input class="checkbox" type="checkbox" name="testc"> This is Item 3</li>
  <li><input class="checkbox" type="checkbox" name="testc"> This is Item 4</li>
  <li><input class="checkbox" type="checkbox" name="testc"> This is Item 5</li>
  <li><input class="checkbox" type="checkbox" name="testc"> This is Item 6</li>
</ul>

The above code is working fine. but here the part below is checking the CSS of the checkboxes to apply the condition. i want to check the name of the checkboxes. Looking for a solution ?

//check "select all" if all checkbox items are checked
 if (document.querySelectorAll('.checkbox:checked').length == checkboxes.length) {
     select_all.checked = true;
     }
 });

Upvotes: 0

Views: 168

Answers (2)

Yukul&#233;l&#233;
Yukul&#233;l&#233;

Reputation: 17062

  1. While change event bubble you can addEventListener on parent element.
  2. Use find() to check if one input is not checked.
  3. If you want to select by name use input[name="testc"]
  4. What about #select_all state if some inputs are checked?
var checkall = document.getElementById("select_all")
var ul = document.querySelector('ul#checkbox-list')
var checkboxes = Array.from(ul.querySelectorAll('input[name="testc"]')) /* 3 */

checkall.addEventListener('change', () => {
  checkboxes.forEach(elm => (elm.checked = checkall.checked))
})

ul.addEventListener('change', () => { /* 1. */ 
  checkall.checked = !checkboxes.find(elm => !elm.checked) /* 2. */ 
})

stronger example here solving /* 4. */: https://codepen.io/yukulele/pen/PNNdvw?editors=0010

Upvotes: 1

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123397

If you want to check the checkboxes by their names then change the selector inside querySelectorAll

if (document.querySelectorAll('[name="testc"]:checked').length == checkboxes.length) {
     select_all.checked = true;
}

Upvotes: 0

Related Questions