0

I have a header checkbox and subsequent "children" checkboxes that are displayed programmatically each time my app loads.

I'm trying to ensure that if the user unchecks all the children boxes, it auto unchecks the header. I map through all checkboxes on the page at the start:

var x = '';
$(document).ready(function() {
  $('.class').map(function () {
    x += ('Yes');
  });
    alert(x);
});

This gives me an array with "Yes" for the number of checkboxes that exist in each section.

I need to be able to slice the array into nothing as the user unchecks boxes within that class. I'm stuck.

Here is my change listener:

$(':checkbox').change(function () {
if(**THE CHECKBOX I AM UNCHECKING HAS THE CLASS**) {
  x.slice(-1);
 } 
});

SOLUTION:

<input class='children' type='checkbox'/>
<input class='children' type='checkbox'/>
<input class='header' type='checkbox'/>

var check_count = $(".children:checked").length;

$(".children").change(function () {
if(!this.checked) {
 if (check_count == 0) {
$(".header").prop("checked", false);
 }
}
 });
Ryan
  • 39
  • 5

2 Answers2

1

You can simply use a jQuery selector that returns the checked checkboxes, and use .length to get the count.

var check_count = $(".children:checked").length;
if (check_count == 0) {
    $(".header").prop("checked", false);
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thank you. this is easy and clean - a lot of other answers were great though as well – Ryan Jan 03 '17 at 18:52
0

May not be the most efficient but something like this may work. Each time a user clicks on a checkbox it looks at all the other ones. If at least one has a check, it says false, and exits. If none are checked, it will uncheck the parent.

$(".childrenCheckBoxes").change(function(){

  $(".childrenCheckBoxes").each(function(){
    if (this.checked)
      return false;
  });
  $("#parentCheckBox").prop('checked', false);
  return true;
});

Edit: Barmar's approach is much cleaner

Loaf
  • 3,011
  • 2
  • 15
  • 25