Anuya
Anuya

Reputation: 8350

Handling checkboxlist inside Repeater control using asp.net

After binding the repeater control, my check box looks like the below,

I have two doubts here:

  1. If I select checkbox of Group 1, all the items under group 1 should be selected. How can I do this ?

  2. And I have "Select ALL" button which when clicked should select all the items of all groups. Since the checkbox is inside the repeater control, I'm not sure how to handle it.

  Group 1
       Item 1
       Item 2

    Group 2
       Item 3
       Item 4

    Group 3
       Item 5 
       Item 6




  ASPX : 

    <ol>
        <asp:Repeater ID="rp_Groups" runat="server" OnItemDataBound="rp_Groups_ItemDataBound">
            <ItemTemplate>
                <ul>
                    <asp:CheckBox RepeatColumns="2" runat="server" ID="chk_Group" Text='<%# Eval("category_type") %>' Value='<%# Eval("service_type_category_id") %>' onclick="OnGroupClick" />

                     <asp:CheckBoxList runat="server" ID="chkServiceType" style="padding-left:20px" DataValueField="ServiceTypeID" DataTextField="Name" EnableViewState="true"
                     ></asp:CheckBoxList>

                  <br />
                </ul>
            </ItemTemplate>
        </asp:Repeater>
    </ol>

<script type="text/javascript">
    function OnGroupClick(group) { 
  for(item in group.getElementsByTagName('input')) {
     item.checked = group.checked;
  }
}

   function selectAll() {
        $("#<%=chkServiceType.ClientID %> input[type=checkbox]").each(function () {
            this.checked = true;
        })
    }
</script>

Upvotes: 0

Views: 4278

Answers (1)

Sain Pradeep
Sain Pradeep

Reputation: 3125

You need to add the checkbox onclick event from repeater Itemdatabound event as follow to call JavaScript function.

protected void rp_Groups_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
         try
        {
            System.Web.UI.WebControls.CheckBox chk =  (System.Web.UI.WebControls.CheckBox)e.Item.FindControl("chk_Group");

            chk.Attributes.Add("onclick", "selectGroupAll("+chk.ClientID+");");
        }
         catch (Exception ex)
         {

         }

    }

Then you need to write function in JavaScript

1) Function to select the group checkbox (I am passing the client id of the checkbox group from the page behind. Now I am finding the all the check box which belong to one group and make them checked true.)

function selectGroupAll(chk) {         


            $(chk).parent().parent().find(":checkbox").attr("checked", true);

        }

2) Select ALL on Button Click

Write function in JavaScript and call it from button click event

function selectAll() {

            $(':checkbox').each(function () {
                this.checked = true;
            });
        }

Button form calling the function

 <input type="button" value="Test" onclick="selectAll();" />

Upvotes: 1

Related Questions