如果选中另一个复选框,则取消选中一组复选框 [英] How to uncheck a group of checkboxes when another checkbox is checked

查看:230
本文介绍了如果选中另一个复选框,则取消选中一组复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我正在开发的网站上创建了一个搜索功能,但我被困在这部分。搜索功能具有类别的列表,用户可以检查或取消选择以筛选项目。选项几乎与 Coursera 实施其搜索功能的方式完全相同。如果选中所有类别选项,并且未选中任何其他内容时,取消选中所有类别复选框,我想取消选中所有其他复选框。

I've created a search function on a website I'm developing but I'm stuck on this part. The search function has a list of categories which the user can check or uncheck in order to filter through the items. The options are almost identical to the way Coursera has implemented their search function. I would like to have all the other checkboxes unchecked when the All Categories option is checked and have the All Categories checkbox unchecked when anything else is unchecked. That sounds a bit confusing but it's exactly what that website has implemented.

这里是一个代码示例:

<div class="filter-grade">
    <label class="checkbox">
        <input type="checkbox" id="grade-all" name="grade[]" value="0" checked><b>All Grades</b>
    </label>
    <label class="checkbox">
        <input type="checkbox" id="grade-9" name="grade[]" value="9">Grade 9
    </label>
    <label class="checkbox">
        <input type="checkbox" id="grade-10" name="grade[]" value="10">Grade 10
    </label>
    <label class="checkbox">
        <input type="checkbox" id="grade-11" name="grade[]" value="11">Grade 11
    </label>
    <label class="checkbox">
        <input type="checkbox" id="grade-12" name="grade[]" value="12">Grade 12
    </label>
</div>


推荐答案

a href =http://jsfiddle.net/ctnCn/5/ =nofollow> http://jsfiddle.net/ctnCn/5/

Despite my comment, I built out a fiddle: http://jsfiddle.net/ctnCn/5/

$('.group input').on('change', function() {
    var $inputs = $(this).siblings('input').add(this),
        $checked = $inputs.filter(':checked'),
        $all = $inputs.eq(0),
        index = $inputs.index(this);

    (index === 0 ? $checked : $all).removeAttr('checked');

    if(index === 0 || $checked.length === 0) {
        $all.attr('checked', 'checked');
    }
});

更新为项目专用: http://jsfiddle.net/ctnCn/6/

$('.filter-grade input').on('change', function() {
    var $inputs = $(this).closest('div').find('input'),

虽然我想指出,这不是标签元素的标准用法,标记以使标签和输入成为同级(并使用id和for属性来链接它们)。参考这个参考: http://www.w3schools.com/tags/tag_label.asp 我以前的小提琴也提供了标准标记约定的示例。

Though I would like to point out that this is not the standard usage of the label element. I would suggest changing your markup to have labels and inputs be siblings (and use the "id" and "for" attributes to link them). Take a look at this reference: http://www.w3schools.com/tags/tag_label.asp My previous fiddle also provides an example of the standard markup convention.

这篇关于如果选中另一个复选框,则取消选中一组复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆