限制c#中网格视图中选中的复选框数
本文关键字:复选框 视图 中网 网格 限制 | 更新日期: 2023-09-27 18:26:16
我需要限制用户在c#asp.net中的GridView上选择的复选框的数量。
我尝试了下面的代码,但我有两个问题:
- 在弹出警报
'Cannot check more than 3 check boxes'
后,始终选中第四个复选框 - 按钮
btn
已启用并验证表单
我错过了什么?
这个代码出了什么问题?
提前谢谢。
<%@ 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>
您需要取消选中第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;
}
}
}
}