當CheckBoxList超過3個的項目被勾選時會跳出警告視窗:在网上找到的一个例子如下:
| html xmlns="http://www.w3.org/1999/xhtml"> | |
| 2 | <head id="Head1" runat="server"> |
| 3 | <title>Untitled Page</title> |
| 4 | |
| 5 | <script type="text/javascript"> |
| 6 | |
| 7 | |
| 8 | function checkCount() |
| 9 | { |
| 10 | cbxList = document.getElementById('<%=cbxListType.ClientID %>'); |
| 11 | |
| 12 | var count = 0; |
| 13 | var IsError = false; |
| 14 | for(i = 0; i < cbxList.all.tags('input').length;i++) |
| 15 | { |
| 16 | if ( cbxList.all.tags('input')[i].type=='checkbox') |
| 17 | { |
| 18 | if ( cbxList.all.tags('input')[i].checked ) |
| 19 | { |
| 20 | count++; |
| 21 | } |
| 22 | } |
| 23 | |
| 24 | if ( count > 3) |
| 25 | { |
| 26 | IsError = true; |
| 27 | break; |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | if ( IsError) |
| 32 | { |
| 33 | alert('最多只能選三個!'); |
| 34 | event.srcElement.checked = false; |
| 35 | } |
| 36 | } |
| 37 | </script> |
| 38 | |
| 39 | </head> |
| 40 | <body> |
| 41 | <form id="form1" runat="server"> |
| 42 | <div> |
| 43 | <asp:CheckBoxList ID="cbxListType" runat="server" RepeatDirection="Horizontal"> |
| 44 | <asp:ListItem Value="a">aaa</asp:ListItem> |
| 45 | <asp:ListItem Value="b">bbb</asp:ListItem> |
| 46 | <asp:ListItem Value="c">ccc</asp:ListItem> |
| 47 | <asp:ListItem Value="d">ddd</asp:ListItem> |
| 48 | <asp:ListItem Value="e">eee</asp:ListItem> |
| 49 | <asp:ListItem Value="f">fff</asp:ListItem> |
| 50 | </asp:CheckBoxList></div> |
| 51 | </form> |
| 52 | </body> |
| 53 | </html> |
| protected void Page_Load(object sender, EventArgs e) | |
| 2 | { |
| 3 | |
| 4 | this.cbxListType.Attributes.Add("onclick", "checkCount();"); |
| 5 | |
| 6 | } |
通过对其JS的修改,可以改变成为如下的JS脚本:
function CheckBoxSelect( objName)
{
var IsCheck=0;
var checkobj = document.getElementById( objName);
var checks = checkobj.getElementsByTagName( "input ");
for(var n=0;n <checks.length;n++)
{
if(checks[n].type== "checkbox " && checks[n].checked==true)
{
IsCheck+=1;
}
}
if(IsCheck==0)
{
alert( "至少要选择1个部门 ");
return false;
}
if(IsCheck>2)
{
alert("最多只能选择2项目");
event.srcElement.checked = false;
return false;
}
return true;
}
本文介绍如何使用JavaScript限制ASP.NET中CheckBoxList控件的最大选中数量,并提供了一个具体的实现示例。

430

被折叠的 条评论
为什么被折叠?



