限制在c#中gridview中选中的复选框数量

时间:2014-10-11 12:59:22

标签: javascript c# asp.net checkbox

我需要在c#asp net中限制用户在GridView上选择的复选框的数量。

我尝试了下面的代码,但我有两个问题:

  1. 警告弹出 'Cannot check more than 3 check boxes' 后,始终会选中复选框号码4;
  2. 启用按钮 btn 并验证表单。
  3. 我错过了什么?

    这段代码出了什么问题?

    提前谢谢。

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <script type="text/javascript">
            function CheckCheck() {
                var chkBoxList = document.getElementById('<%=GridView1.ClientID %>');
                var chkBoxCount = chkBoxList.getElementsByTagName("input");
    
                var btn = document.getElementById('<%=btn.ClientID %>');
                var i = 0;
                var tot = 0;
                for (i = 0; i < chkBoxCount.length; i++) {
                    if (chkBoxCount[i].checked) {
                        tot = tot + 1;
                    }
                }
    
                if (tot > 3) {
                    alert('Cannot check more than 3 check boxes');
                }
            }
    
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
                <Columns>
                    <asp:TemplateField>
                        <ItemTemplate>
                            <asp:CheckBox ID="cbSelProduct" runat="server" onclick="javascript:CheckCheck();" />
                            <asp:HiddenField ID="HiddenField1" runat="server" Value='<%#Eval("name")%>' />
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:BoundField ItemStyle-Width="250px" DataField="name" HeaderText="name" />
                </Columns>
            </asp:GridView>
            <asp:Button runat="server" ID="btn" Text="Send" OnClick="btn_Click" />
        </div>
        </form>
    </body>
    </html>
    

1 个答案:

答案 0 :(得分:1)

您需要取消选中第4个已选中的复选框:

function CheckCheck()
{
    var chkBoxList = document.getElementById('<%=GridView1.ClientID %>');
    var chkBoxCount = chkBoxList.getElementsByTagName("input");

    var btn = document.getElementById('<%=btn.ClientID %>');
    var i = 0;
    var tot = 0;
    for (i = 0; i < chkBoxCount.length; i++)
    {
        if (chkBoxCount[i].checked)
        {
            tot = tot + 1;

            if (tot > 3)
            {
                alert('Cannot check more than 3 check boxes');
                chkBoxCount[i].checked = false;
                return;
            }
        }
    }
}