user1272433
user1272433

Reputation: 157

Limit number of checked checkboxes using iCheck

I'm using iCheck to style checkboxes and I'm having trouble using this along side validation. Basically I need to allow 3 checkboxes to be checked at a time and prevent further boxes from being checked.

I've tried using this:

$("#modal1").on("change", function()
{
  var limit = 3,
      checkboxes = $(this).find("input:checkbox"),
      valid = checkboxes.filter(":checked").length >= limit;

    checkboxes.not(":checked").attr("disabled", valid);
    $('input').iCheck('update');
});

It works without iCheck as seen below, but I can't get iCheck to update.

http://jsfiddle.net/hUdrF/4/

Upvotes: 0

Views: 2131

Answers (3)

Rahul Tathod
Rahul Tathod

Reputation: 348

make some changes in code

    $("#modal1").on("change", function()
    {
    var limit = 2;
    $('.check').on('ifChanged', function(event) {
        checkboxes = $('.icheck-list').find("input:checkbox");
        if (checkboxes.filter(":checked").length >= limit) {
            checkboxes.not(":checked").iCheck('disable');
        } else {
            checkboxes.not(":checked").iCheck('enable');
        }
    });
    });

Upvotes: 0

user1272433
user1272433

Reputation: 157

I up adding .on("ifToggled" plus SpaceDog's code, which solved the problem.

$("#modal1").on("ifToggled", function() {
    checkboxes = $(this).find("input:checkbox");  
    if (checkboxes.filter(":checked").length >= 3) { 
        checkboxes.not(":checked").iCheck('disable'); 
    } else { 
        checkboxes.not(":checked").iCheck('enable');
    } 
});

Upvotes: 4

SpaceDog
SpaceDog

Reputation: 3269

It looks like the iCheck update method isn't seeing the change to the disabled attribute. You could try the native iCheck method for disabling a checkbox:

if (checkboxes.filter(":checked").length >= limit) { 
    checkboxes.not(":checked").iCheck('disable'); 
} else {
    checkboxes.not(":checked").iCheck('enable'); 
}

Upvotes: 2

Related Questions