利用 JavaScript 去限制 CheckBoxList 的勾選數

来源:互联网 发布:在线播放源码 编辑:程序博客网 时间:2024/05/20 01:47

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

原创粉丝点击