How to uncheck “select all” checkbox when all item unchecked?

I am trying to make select all checkboxes, and I’m stuck in some problem.

How to uncheck “select all” checkbox when all item unchecked?

This is what I tried code.

<input id="select-all" type="checkbox" name="select-all-cam">
<span class="txt-label">Select All</span>
<div class="list">
  <ul>
  <li>
      <input id="cam-1" type="checkbox" name="select-cam">
      <label for="cam-1">item1</label>
  </li>
  <li>
      <input id="cam-2" type="checkbox" name="select-cam">
      <label for="cam-2">item2</label>
  </li>


  </ul>
</div>
$('#select-all').click(function(event) {
  if (this.checked) {
    $('.list input[type="checkbox"]').each(function() {
        this.checked = true;
    });
  } else {
    $('.list input[type="checkbox"]').each(function() {
        this.checked = false;
    });
  }
});

Demo: https://fiddle.jshell.net/0j19t3g5/


solution

You could add a change event listener to the checkbox elements in .list and determine if the number of checked checkboxes is the same as the total number.

Updated Example

$('.list input[type="checkbox"]').on('change', function () {
  var allChecked = $('.list input:checked').length === $('.list input').length;
  $('#select-all').prop('checked', allChecked);
});

The benefit to this approach is that the ‘Select All’ checkbox is checked if all the other checkboxes are checked, and likewise it is unchecked if one of them is unchecked.

I also changed the click event listener to a change event listener. You can also shorten your initial event listener to the following:

$('#select-all').on('change', function() {
  $('.list input[type="checkbox"]').prop('checked', this.checked);
});