Search code examples
javascriptjqueryasp.netrepeatercheckboxlist

Set maximum selected per CheckBoxList in Repeater


I have a dynamic CheckBoxList inside a Repeater:

<asp:Repeater ID="rpt1" runat="server" OnItemDataBound="rpt1_ItemDataBound">
  <ItemTemplate>
    <asp:HiddenField ID="hf1" runat="server" Value='<%# Eval("Id") %>' />
    <asp:TextBox ID="txt" runat="server" Text='<%# Eval("Question") %>'></asp:TextBox>
    <asp:CheckBoxList ID="chk1" runat="server" Width="100%" RepeatColumns="3" RepeatLayout="Table" RepeatDirection="Horizontal></asp:CheckBoxList>
  </ItemTemplate>
</asp:Repeater>

I want the user to only choose/select 3 items. I tried many solutions, including this one:

var limit = 10;
$(function () {
    $('[id*="chk1"]').on('change', function (evt) {
        if ($('[id*="chk1"]:checked').length > limit) {
            this.checked = false;
            alert('You can only choose ' + limit);
        }
    });
});

It does work, but if the Repeater has more than one CheckBoxList generated, the limit still counts if I select another item in a different CheckBoxList.

That means if I choose 8 items in CheckBoxList number one, then I can only choose 2 items in CheckBoxList number two, but the goal is to limit selected items to 10 on each CheckBoxList.

Any solution?


Solution

  • Change $('[id*="chk1"]:checked') to:

    $(this).parent().closest('[id*=rpt1]').find('[id*="chk1"]:checked')
    

    Tested against:

    <table id="MainContent_rpt1_chk1_0">
      <tbody>
        <tr>
          <td>
            <input id="MainContent_rpt1_chk1_0_0_0" type="checkbox" />
          </td>
          <td>
            <input id="MainContent_rpt1_chk1_0_1_0" type="checkbox" />
          </td>
        </tr>
      </tbody>
    </table>
    <table id="MainContent_rpt1_chk1_1">
      <tbody>
        <tr>
          <td>
            <input id="MainContent_rpt1_chk1_0_0_0" type="checkbox" />
          </td>
          <td>
            <input id="MainContent_rpt1_chk1_0_1_0" type="checkbox" />
          </td>
        </tr>
      </tbody>
    </table>