0

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

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/

4

1 回答 1

2

比较lengthofchildCheckBoxlengthof:checked的:

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

这是一个小提琴

于 2013-10-28T21:25:41.440 回答