【问题标题】:group checkboxes - how to uncheck the parent box if any child boxes are unchecked?组复选框 - 如果未选中任何子框,如何取消选中父框?
【发布时间】:2013-10-28 21:19:06
【问题描述】:

我有一个将子复选框分组在父复选框下的脚本。它工作得很好,除了我希望父复选框 unchecked 如果 any 子复选框未选中。如果所有子框都被选中,那么父复选框也应该被选中。我将如何实现这一目标?

HTML:

<form>
<fieldset>
<input type="checkbox" class="parentCheckBox" /> Africa
<div class="content">
<input type="checkbox" value="" name="countries" class="childCheckBox" /> Algeria<br />
<input type="checkbox" value="" name="countries" class="childCheckBox" /> Angola<br />
</div>
</fieldset>
<fieldset>
<input type="checkbox" class="parentCheckBox" /> North America
<div class="content">
<input type="checkbox" value="" name="countries" class="childCheckBox" /> Canada<br />
<input type="checkbox" value="" name="countries" class="childCheckBox" /> United States<br />
</div>
</fieldset>
</form>

Javascript:

$(document).ready(
    function() {
        //clicking the parent checkbox should check or uncheck all child checkboxes
        $(".parentCheckBox").click(
            function() {
                $(this).parents('fieldset:eq(0)').find('.childCheckBox').prop('checked', this.checked);
            }
        );
        //clicking the last unchecked or checked checkbox should check or uncheck the parent checkbox
        $('.childCheckBox').click(
            function() {
                if ($(this).parents('fieldset:eq(0)').find('.parentCheckBox').attr('checked') == true && this.checked == false)
                    $(this).parents('fieldset:eq(0)').find('.parentCheckBox').attr('checked', false);
                if (this.checked == true) {
                    var flag = true;
                    $(this).parents('fieldset:eq(0)').find('.childCheckBox').each(
                        function() {
                            if (this.checked == false)
                                flag = false;
                        }
                    );
                    $(this).parents('fieldset:eq(0)').find('.parentCheckBox').attr('checked', flag);
                }
            }
        );
    }
); 

小提琴:http://jsfiddle.net/TRTMS/4/

【问题讨论】:

    标签: javascript jquery checkbox


    【解决方案1】:

    比较childCheckBoxlength:checkedlength

    $('input.parentCheckBox').prop('checked', $('input.childCheckBox').length === $('input.childCheckBox:checked').length); 
    

    Here's a fiddle

    【讨论】:

    • 效果很好!我只有一个问题。我在同一页面上有几组组。它在重新检查所有子框时适用于第二组,以便再次检查父框,但它似乎不适用于第一个。
    • 是的,效果很好!太感谢了!我会以你的名字命名我的长子:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-16
    • 2013-12-06
    • 2017-05-26
    相关资源
    最近更新 更多