create a select all checkbox for every three checkboxes

create a select all checkbox for every three checkboxes

i display many chackboxes organized in three columns in my razor view and i want to create a select all checkbox for every three checkboxes (every row):

 <table>
            <tr>
                @{
                    int cnt = 0;
                    string sr =null;
                    string j = null;
                    string k = null;
                    List<Security.Models.AssignedRolesVM> Roles = ViewBag.tp_role;

                    foreach (var role in Roles)
                    {
                        if (cnt++ % 3 == 0)
                        { sr=cnt.ToString();
                          j =(cnt+1).ToString();
                         @:</tr><tr>
                             @: <td><input type="checkbox" id=j  /></td>
                               
                        }
                        k=cnt.ToString();
                        @:<td>
                            <input type="checkbox"
                               name=sr
                               class="checked"
                               value="@role.RoleID"
                               @(Html.Raw(role.Assigned ? "checked=\"checked\"" : "")) />
                               @role.RoleID @:  @role.Name
                        @:</td>
                    }
                    @:</tr>
                }
        </table>

here is my script:

     <script src="~/Scripts/jquery-1.10.2.min.js">
                                </script>
                                <script type="text/javascript">
                                    $(function () {
                                        $(j).click(function () {
                                            $('input[name=sr]').prop("checked", $(this).prop("checked"));
                                        });
                                        $('input[name=sr]').click(function () {
                                            if ($('input[name=sr]').length == $('input[name=sr]:checked').length) {
                                                $(j).prop("checked", "checked");
                                            }
                                            else {
                                                $(j).removeProp("checked");
                                            }

                                        });
                                    });
     </script>

input[name=sr] should refer to every three checkboxes with the same name, since it changes every time cnt%3=0, i really can't figure out the problem.