Select all checkbox with icheck

user1896653 picture user1896653 · Feb 27, 2015 · Viewed 16.4k times · Source

I am using iCheck plugin for checkbox. I put a "Select all" functionality at there. The structure:

  • Select all
  • Checkbox 1
  • Checkbox 2
  • Checkbox 3

It works fine like when check on "Select all", all the checkboxes will checked. when uncheck "Select all", all the checkboxes will unchecked. But, after checking "Select all", if making any checkbox unchecked, "Select all" should be unchecked too automatically as at that time all checkbox are not checked.

To make this, I have written this:

$('#check-all').on('ifChanged', function(event){
    if($('.check').filter(':checked').length == $('.check').length) {
        $('#check-all').iCheck('check');
    } else {
        $('#check-all').iCheck('uncheck');
    }
    $('#check-all').iCheck('update');
});

But, after putting this code, my checkboxes are not working fine like "Select all" doesn't work with single click, it need multiple click often. Also "Select all" is not unchecking when any single checkbox is unchecked. What's the problem with the code? How to write it correctly?

Fiddle work

Answer

harshtuna picture harshtuna · Feb 27, 2015
// Remove the checked state from "All" if any checkbox is unchecked
$('.check').on('ifUnchecked', function (event) {
    $('#check-all').iCheck('uncheck');
});

// Make "All" checked if all checkboxes are checked
$('.check').on('ifChecked', function (event) {
    if ($('.check').filter(':checked').length == $('.check').length) {
        $('#check-all').iCheck('check');
    }
});

handling $('#check-all').on('ifUnchecked', ... is tricky though - it fires the other handling and every checkbox gets unchecked

fiddle