问题
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