CheckBox检查所有子复选框

时间:2016-06-06 14:54:56

标签: javascript jquery asp.net-mvc

我只想在检查父项时检查所有子复选框,并在取消选中父项时取消选中。

THX

<div class="modal-body">

            @for (int i = 0; i < Model.Count; i++)
            {
                @Html.HiddenFor(m => Model[i].Id)
                <div id="@Model[i].Name" class="row" style="width:300px;">
                    <div>
                        <span data-toggle="collapse" class="glyphicon glyphicon-chevron-down" data-target="#@Model[i].Id"> </span>
                        @Html.Label(Model[i].Name + "("+ (Model[i].LicensesTotal - Model[i].LicensesUsed).ToString()+"/" + Model[i].LicensesTotal.ToString()))


                        @Html.CheckBoxFor(x => Model[i].Assigned, new { @class = "pull-right",  @id = @Model[i].Name.ToString() })
                    </div>
                    <div id="@Model[i].Id" class="collapse">


                        @for (int i2 = 0; i2 < Model[i].Plans.Count; i2++)
                        {
                            <div>
                                <div>
                                    @Html.Label(Model[i].Plans[i2].Name)
                                    @Html.CheckBoxFor(x=> Model[i].Plans[i2].Assigned, new { @class = "pull-right" })
                                </div>
                            </div>
                        }
                    </div>
                    <hr/>
                </div>

            }

</div>

1 个答案:

答案 0 :(得分:1)

将一个特殊类添加到父复选框,如下所示

 @Html.CheckBoxFor(x => Model[i].Assigned, new { @class = "pull-right parent",  @id = @Model[i].Name.ToString() })

然后你的代码就是,

$(".parent").change(function() {
  $(this).closest(".row").find(".collapse :checkbox").prop("checked", this.checked);
});
  • 使用row
  • 找到包含课程closest(".row")的父div
  • 使用.find(".collapse :checkbox")获取div折叠中的所有复选框(查找将搜索子元素)