例如,如果我在给定示例中选中所有类别复选框,则应取消选中所有剩余复选框,如果我选中一个或多个剩余类别,则应取消选中所有类别复选框。
HTML
<div class="search-dropdown">
<input type="checkbox" class="checkbox all-categories" name="all-categories" id="all-categories" value="" /><label for="keys">All categories</label>
<hr>
<ul class="checkboxlist_list">
<li><input type="checkbox" class="checkbox electical" /><label>electrical</label><br/></li>
<li><input type="checkbox" class="checkbox mechanical" /><label>mechanical</label><br/></li>
<li><input type="checkbox" class="checkbox construction"/><label>construction</label><br/></li>
</ul>
</div>
<p class="category-holder">Select Category</p>
的Javascript
$('.search-dropdown input[type="checkbox"]').on("change", function(){
var categories = [];
$('.checkbox:checked').each(function(){
var category = $(this).next().text();
categories.push(category);
});
$(".category-holder").html(categories.join(", "));
if (!$(".category-holder").text().trim().length) {
$(".category-holder").text("Select Category");
}
});
答案 0 :(得分:1)
您可以将这些代码行添加到change
事件处理程序中:
if($(this).is('.all-categories:checked')){
$('.checkboxlist_list .checkbox').prop('checked', false);
return $(".category-holder").text($(this).next().text());
}
$('.all-categories').prop('checked', false);
// ... the rest of your code ...
Optionaly(甚至更好),您可以将所有复选框设置为:checked
,并在.all-categories
复选框为:checked
时禁用它们
if($(this).is('.all-categories:checked')){
$('.checkboxlist_list .checkbox').prop({'checked': 1, 'disabled' : 1});
return $(".category-holder").text($(this).next().text());
}else if($(this).is('.all-categories')){
$('.checkboxlist_list .checkbox').prop('disabled', 0);
}
// ... the rest of your code ...
答案 1 :(得分:0)
试试这个,它在JS中。
function checkAll(ele) {
var checkboxes = document.getElementsByTagName('input');
if (ele.checked) {
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].type == 'checkbox') {
checkboxes[i].checked = true;
}
}
} else {
for (var i = 0; i < checkboxes.length; i++) {
console.log(i)
if (checkboxes[i].type == 'checkbox') {
checkboxes[i].checked = false;
}
}
}
}
<input type='checkbox' name='select_all' onClick='javascript:checkAll(this)'>
答案 2 :(得分:0)
您可以尝试检查当前元素点击的ID是all-categories
如果是,请使用`removeAttr()取消选中checkboxlist_list
类中的所有复选框:
if($(this).attr('id')=='all-categories'){
$('.checkboxlist_list .checkbox').removeAttr('checked')
}