Search code examples
c#jqueryasp.netwebformsasprepeater

Creating a Label for a checkbox inside a repeater


<asp:Repeater runat="server" ID="Repeater1" OnItemDataBound="countryDataBound">
  <HeaderTemplate>        
  </HeaderTemplate>
  <ItemTemplate>
    <div class="accordion">
      <span><h3><%# Eval("key") %>
      <div class="panelCountry">
        <input type="checkbox" runat="server" class="chbSelectAll"/><label>SelectAll</label>
        <asp:CheckBoxList 
           ID="chbListCountries" 
           CssClass="chbList"
           RepeatColumns="4" 
           RepeatDirection="Horizontal" 
           DataTextField ="Name"
           DataValueField = "CountryCode"
           runat="server">
           <asp:ListItem></asp:ListItem>
         </asp:CheckBoxList>
     </div> 
  </div>
  </ItemTemplate>
  <FooterTemplate>
  </FooterTemplate>
</asp:Repeater>

I have a dialog containing a repeater of all the countries in the world grouped by continent. Each continent is separated by a jquery accordion. Inside each accordion there is a checkboxlist of countries, with a checkbox at the top that functions as a select all. I need to have the label associated with the select all, be responsive. By this i mean if i click the label i need to be able to trigger the checkbox to select all. I considered

<label for="IDHERE">Select all</label>

I cannot however figure out how to correctly target the checkbox so that when i click the specific label it only selects the check boxes in this specific checkboxlist.

Is there anyway to create an ID for each "select all" checkbox that is unique from the other seven so that when the label is clicked on it correclty selects the checkboxes in its respective accordion. for reference, when the checbox is clicked this javascript runs:

$(document).on('change', '.chbSelectAll', function (e) {
   var selectAllValue = $(this).prop('checked') 
   var panel = $(this).closest('.panelCountry');
   var checkboxes = panel.find('input[type=checkbox]:not(.chbSelectAll)');
   checkboxes.prop('checked',selectAllValue);                             
 });

Visual view of the problem


Solution

  • If you don't need the runat=server tag you can create your own label for= by using the ItemIndex.

    <input type="checkbox" class="chbSelectAll" id="CheckBox_<%# Container.ItemIndex %>" />
    <label for="CheckBox_<%# Container.ItemIndex %>">SelectAll</label>
    

    But why not use an aspnet CheckBox? Then you won't have that problem anyway.

    <asp:CheckBox ID="CheckBox1" runat="server" Text="SelectAll" CssClass="chbSelectAll" />