如何在jQuery中仅检查所有类别复选框或其他重新映射类别复选框

时间:2016-10-06 11:59:12

标签: javascript jquery checkbox

例如,如果我在给定示例中选中所有类别复选框,则应取消选中所有剩余复选框,如果我选中一个或多个剩余类别,则应取消选中所有类别复选框。

Here is the jsfiddle

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

3 个答案:

答案 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 ...

JSFiddle

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 ...

JSFiddle

答案 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')
}