我要单击“全选”,它将禁用/淡出其余选项。但是,如果未选中“全选”,则执行代码说明的所有操作。
我究竟做错了什么?
$(function() {
$("input[type=checkbox]").change(function() {
var count_checkbox = $("input[type=checkbox]:checked").length;
var disable_checkbox = $("input[type=checkbox]:checked").length >= 3;
if ($("input.category_all:checked").is(':checked')) {
$("input[type=checkbox]").not(":checked").attr("disabled",disable_checkbox);
}
$("input[type=checkbox]").not(":checked").attr("disabled",disable_checkbox);
if(count_checkbox > 0){
$('#checkbox_counter').replaceWith('<div id="checkbox_counter">'+count_checkbox+' Selected</div>');
}else{
$('#checkbox_counter').replaceWith('<div id="checkbox_counter">Select...</div>');
}
});
});
好的,disable_checkbox
布尔值出了问题-仅当您检查了三个或更多项(尝试检查b,c和d会看到)时,它才是正确的,但此时“全选”实际上并没有全部选择。
这是基于您自己的更优雅的解决方案
$(function() {
$("input[type=checkbox]").change(function() {
var count_checkbox_all = $("input[type=checkbox]").not(".category_all").length;
var count_checkbox_checked = $("input[type=checkbox]:checked").not(".category_all").length;
if ($(this).hasClass("category_all")) {
//if we clicked on "Select All"
var is_checked = $(".category_all").is(":checked");
//check/uncheck everything and disable/enable the rest of the tickboxes based on the state of this one
$(".categories_list").prop("checked", is_checked).attr("disabled", is_checked);
//also update the count of checked items
count_checkbox_checked = $("input[type=checkbox]:checked").not(".category_all").length;
}
if (count_checkbox_checked == count_checkbox_all) { //if all have been checked
//make sure they are disabled and that "Select All" is checked as well
$(".categories_list").attr("disabled", true);
$(".category_all").prop("checked", true);
}
if(count_checkbox > 0){
$('#checkbox_counter').replaceWith('<div id="checkbox_counter">'+count_checkbox+' Selected</div>');
}else{
$('#checkbox_counter').replaceWith('<div id="checkbox_counter">Select...</div>');
}
});
});
您可以在此处查看其运行情况:JS Fiddle
如果单击“全选”,则它将选中所有复选框(因为之后将对选中的复选框进行计数),然后将其禁用。如果取消选中它,则它将清除复选框的复选框并启用它们。此后将执行计数,并且不包括“全选”复选框,因为从概念上讲,您只有4个选项-计算第5个选项没有多大意义
编辑根据@Tyblitz的评论,现在当您单独选择所有复选框时,将获得单击“全选”的效果。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句