利用 JavaScript 去限制 CheckBoxList 的勾選數

當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> 
 其CS页面代码如下:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值