判断CheckBoxList必须选中一个

cheng525jj 2011-03-07 04:47:27
1.网上有看到有一种用javascript控制的,不知道如何去用它,页面上有多个CheckBoxList.最好是能修改成一个通用的isselect(Checkbox1)
页面的按钮onclick事件已经写了后台代码.
<script language="javascript" type="text/javascript">
function isselect()
{
var dutyflag=0;
var checkobj = document.getElementById( "CheckBoxList");
var checks = checkobj.getElementsByTagName( "input");
for(var n=0;n <checks.length;n++)
{
if(checks[n].type== "checkbox " && checks[n].checked==true)
{
dutyflag=1;
}
}
if(dutyflag==0)
{
alert( "至少要选择1个选项 ");
return false;
}
return true;
}
</script>

2.如果是在后台控制,代码应该如何写,请高人指点!
...全文
255 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
lnsky2010 2011-06-09
  • 打赏
  • 举报
回复
这个好!!![Quote=引用 7 楼 tao145 的回复:]
aspx:

HTML code
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>无标题页</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:CheckBox……
[/Quote]
lnsky2010 2011-06-09
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 cheng525jj 的回复:]
HJ_daxian
是否完整给一个小Demo
[/Quote]这个很受用!
lnsky2010 2011-06-09
  • 打赏
  • 举报
回复
太厉害了 很受用 顶起来
笑道江湖情 2011-03-07
  • 打赏
  • 举报
回复
aspx:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>无标题页</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:CheckBoxList ID="CheckBoxList1" runat="server">
<asp:ListItem Value="1" Text="CheckBox1"></asp:ListItem>
<asp:ListItem Value="2" Text="CheckBox2"></asp:ListItem>
<asp:ListItem Value="3" Text="CheckBox3"></asp:ListItem>
<asp:ListItem Value="4" Text="CheckBox4"></asp:ListItem>
</asp:CheckBoxList>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</div>
</form>
</body>
</html>



cs:
protected void Button1_Click(object sender, EventArgs e)
{
int count=0;
foreach (ListItem item in this.CheckBoxList1.Items)
{
if (item.Selected)
{
count++;
}
}
if (count == 0)
{
Response.Write("<script>alert('必须选择一项!')</script>");
return;
}
}
cheng525jj 2011-03-07
  • 打赏
  • 举报
回复
HJ_daxian
是否完整给一个小Demo
ycproc 2011-03-07
  • 打赏
  • 举报
回复
循环遍历
checked的 count 必须大于1
michaelgong 2011-03-07
  • 打赏
  • 举报
回复
3楼的可以。。。
定义一个计时器
循环完之后,判断这个计时器是否大于0,如果大于0,就说明至少有一个选中。。。。
  • 打赏
  • 举报
回复


int _num = 0;
foreach (Control ct in this.Controls)
{
if(ct is CheckBox)
{
if(((CheckBox)ct).Checked)
{
num++;
}
}
}
if(num > 0)
{
}
else
//提示至少要选择1个选项
huwaihutu 2011-03-07
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 hj_daxian 的回复:]
foreach遍历
[/Quote]
如果有item被checked了就证明选中了
  • 打赏
  • 举报
回复
foreach遍历

62,074

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧