Limit number of checked checkboxes using iCheck

狂风中的少年 提交于 2020-01-06 15:18:11

问题


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/


回答1:


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');
    } 
});



回答2:


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'); 
}



回答3:


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');
        }
    });
    });


来源:https://stackoverflow.com/questions/18906657/limit-number-of-checked-checkboxes-using-icheck

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!