0

I simply wanna check all child checkBox when parent is check and uncheck when parent is uncheck.

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>
2
  • Write html result element instead of razor. Commented Jun 6, 2016 at 14:55
  • Its dynamically generated so you cant assume the html result will be always the same... Commented Jun 6, 2016 at 14:57

1 Answer 1

1

Add a special class to the parent checkbox like this,

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

Then your code will be,

$(".parent").change(function() {
  $(this).closest(".row").find(".collapse :checkbox").prop("checked", this.checked);
});
  • find the parent div with class row using closest(".row")
  • Get all the checkboxes inside the div collapse using .find(".collapse :checkbox") (Find will search for the child elements)
Sign up to request clarification or add additional context in comments.

11 Comments

I have this $(":checkbox").change(function (e) to detect the Id
@FrankSharp then add a special class to the parent checkbox.
@FrankSharp see the answer now.
The class event is detected but $(this).closest(".row").find(".collapse :checkbox").prop("checked", this.checked); not work
try alert((this).closest(".row").find(".collapse :checkbox").length) and let me know the result
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.