ASP.NET中用js取CheckBoxList中值的方法实例

时间:2022-09-25 21:07:02

做的一些项目都比较小,而且时间紧,有好多东西都没来得急总结,趁这会还有点时间把前面项目中的用到的知识点分享下,只为以后方便使用。
前台页面代码

复制代码代码如下:

<!--关键字-->
    <div id="keyWordsDiv" style="border: 2px solid #6FA1D9; display: none; position: absolute;
        top: 0px; left: 0px; width: 260px; height: 120px; z-index: 3; background-color: #EAF1FD;">
        <div style="width: 260px; height: 20px; background-color: #6FA1D9">
            <ul style="cursor: pointer; line-height: 20px;">
                <li style="float: right" onclick="getCheckVale()">[确定]</li><li style="float: right"
                    onclick="closeSelf()">[关闭]</li></ul>
        </div>
        <div>
            <asp:CheckBoxList ID="cblKeyWords" runat="server" RepeatColumns="2">
            </asp:CheckBoxList>
        </div>
    </div>


js脚本

复制代码代码如下:

//打开关键词窗口
function  locking(e)
{      
    var divLeft = e.offsetLeft;
    var divTop = e.offsetTop;
    while(e=e.offsetParent)  
    {  
         divLeft   +=   e.offsetLeft;    
         divTop   +=   e.offsetTop;  
    }      
    var divObj = document.getElementById("keyWordsDiv");   
    divObj.style.left = divLeft+"px";
    divObj.style.top = divTop+20+"px";
    divObj.style.display = "block";  
}
//关闭关键词窗口
function  closeSelf()
{
    document.all.keyWordsDiv.style.display = 'none';
    var objCheck = document.getElementById("cblKeyWords").getElementsByTagName("input");
    for (var i = 0; i < objCheck.length; i++) {
        document.getElementById("cblKeyWords_" + i).checked = false;
    }
    return false;     
}
//关键词取值
function getCheckVale()
{
//var objCheck=document.getElementById("cblKeyWords");
var objCheck=document.getElementById("cblKeyWords").getElementsByTagName("input");
var objLabel = document.getElementById("cblKeyWords").getElementsByTagName("label")
var txtKeyWordsValue = "";
var m=0
for(var i=0;i<objCheck.length;i++)
{
      if(document.getElementById("cblKeyWords_"+i).checked)
      {
        var idCheck =document.getElementById("cblKeyWords_"+i).id;//当前选择checkbox的ID
        for(var j = 0;j <objLabel.length;j++)
        {
            var forvalue=objLabel[j].getAttributeNode("for").value              
            if(forvalue == idCheck)
            {  
               m+=1;
               for(var k=0;k<m;k++)
               {
               if(k==m-1)
               {
                    txtKeyWordsValue+=objLabel[j].innerHTML;
               }
               else
               {
                    txtKeyWordsValue +="|"+objLabel[j].innerHTML;
                    break;
                }
                }
            }
        }
      }     
}
document.getElementById("txtKeyWords").value=txtKeyWordsValue;
document.all.keyWordsDiv.style.display='none';
}


添加一个按钮调用js

复制代码代码如下:

<asp:TextBox ID="txtKeyWords" runat="server" ReadOnly="True" class="inp"></asp:TextBox>
<input id="imgkey" type="button" runat="server" onclick="locking(this)" class="tailBut"  value="选 择" />


 好了,代码就这么多,点击按钮后弹出层,选中复选框后确实就可以取到值了