设置Repeater中每个CheckBoxList选择的最大值

时间:2017-11-29 08:33:09

标签: javascript jquery asp.net repeater checkboxlist

我在CheckBoxList内有动态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>

我希望用户只选择/选择3个项目。我尝试了很多解决方案,包括这个:

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);
        }
    });
});

它确实有效,但如果Repeater生成了多个CheckBoxList,那么如果我选择其他CheckBoxList中的其他项,则该限制仍然有效。

这意味着如果我在CheckBoxList第一个中选择了8个项目,那么我只能在CheckBoxList个第二个中选择2个项目,但目标是将每个项目限制为10 {{1 }}

任何解决方案?

1 个答案:

答案 0 :(得分:0)

$('[id*="chk1"]:checked')更改为:

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

经过测试:

<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>