Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select all checkbox with icheck

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

like image 631
user1896653 Avatar asked Feb 27 '15 20:02

user1896653


People also ask

How do I select all checkboxes with one checkbox?

In order to select all the checkboxes of a page, we need to create a selectAll () function through which we can select all the checkboxes together. In this section, not only we will learn to select all checkboxes, but we will also create another function that will deselect all the checked checkboxes.

How do I uncheck the select all checkbox?

Clicking on the master checkbox selects all checkboxes; and unchecking it, deselects all checkboxes.


1 Answers

// 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

like image 79
harshtuna Avatar answered Nov 02 '22 23:11

harshtuna