Using jquery check/uncheck SelectAll checkbox when all the checkboxes in the group are checked/unchecked

There are a lot of ways to do this. I suggest making use of .is() when you want to check if a item is checked or not.

Also, split up your work a little bit. Check one then two. Would not suggest you try to bank them together.

Working Example: https://jsfiddle.net/Twisty/awnxx4zL/2/

JavaScript

$(function() {
  $("#one_select_all").change(function() { //"select all" change 
    $(".one_checkbox").prop('checked', $(this).prop("checked")); //change all ".checkbox" checked status
  });

  $("#two_select_all").change(function() { //"select all" change 
    $(".two_checkbox").prop('checked', $(this).prop("checked")); //change all ".checkbox" checked status
  });

  //".checkbox" change 
  $('.one_checkbox, .two_checkbox').change(function() {
    //uncheck "select all", if one of the listed checkbox item is unchecked
    if (!$(this).is("checked") && $(this).hasClass("one_checkbox")) {
      //if this item is unchecked
      $("#one_select_all").prop('checked', false);
      //change "select all" checked status to false
    }
    if ($('.one_checkbox:checked').length == $('.one_checkbox').length) {
      $("#one_select_all").prop('checked', true);
    }
    if (!$(this).is("checked") && $(this).hasClass("two_checkbox")) {
      //if this item is unchecked
      $("#two_select_all").prop('checked', false);
      //change "select all" checked status to false
    }
    if ($('.two_checkbox:checked').length == $('.two_checkbox').length) {
      $("#two_select_all").prop('checked', true);
    }

  });
});

Leave a Comment