Compare the number of total checkboxes to the number of checked checkboxes?

256
January 04, 2017, at 02:19 AM

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);
 }
}
 });
Answer 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);
}
Answer 2

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

Rent Charter Buses Company
READ ALSO
Set filter value in angularJS

Set filter value in angularJS

I have three buttons on my request pageOpen, Close and All

49
VBA - scraping date stamp from website throws error 91

VBA - scraping date stamp from website throws error 91

I'm trying to get scrape values from a site, and I'd like to get the date they were entered, the "as of" datethe HTML code looks like this:

53
Visual Code - preview by opening the browser using its GUI

Visual Code - preview by opening the browser using its GUI

is there any way how to preview HTML file by opening the browser automatically in its GUI? I mean like clicking some button there so it opens tab in browser? Going to my project's directory and opening indexhtml is just too weird

51
Setting a default value for @Html.TextAreaFor()

Setting a default value for @Html.TextAreaFor()

I am using aspnet core razor engine

17