js获取CheckBoxList选中的值


由于这几天要做项目中要通过js获取CheckBoxList选中的值,一开始在网上找了好多都是通过添加CheckBoxList的Attributes来实现,看起来感觉有点麻烦,故自己想了下也是通过添加Attributes来实现,但是通过添加item的Attributes不是CheckBoxList的Attributes。

以下是具体的实现方法:

后台代码:

 1     protected void Page_Load(object sender, EventArgs e)
 2     {
 3         IList<test> testList = new List<test>();
 4         for (int i = 0; i < 10; i++) {
 5             test t = new test();
 6             t.Name = "name"+i;
 7             t.Code = "code" + i;
 8             testList.Add(t);
 9 
10             CheckBoxList1.DataSource = testList;
11             CheckBoxList1.DataTextField = "name";
12             CheckBoxList1.DataValueField = "code";
13             CheckBoxList1.DataBind();
14             
15         }
16     }
17 
18    protected void CheckBoxList1_DataBound(object sender, EventArgs e)
19     {
20         foreach (ListItem item in CheckBoxList1.Items)
21         {
22             item.Attributes["valueCode"] = item.Value;
23         }
24     }

主要是通过DataBound的时候设置item的Attributes

前台页面代码:

1         <asp:CheckBoxList ID="CheckBoxList1" runat="server" OnDataBound="CheckBoxList1_DataBound">
2         </asp:CheckBoxList>
3         <input id="Button1" type="button" value="button" onclick="getCheckValue();" />

脚本代码:

 1     <script type="text/javascript" language="javascript">
 2         function getCheckValue() {
 3             var chkObject = document.getElementById("CheckBoxList1");
 4             var chkInput = chkObject.getElementsByTagName("input");
 5             var item="";
 6             for (var i = 0; i < chkInput.length; i++) {
 7                 if (chkInput[i].checked) {
 8                     item += chkInput[i].parentNode.valueCode + ",";
 9                 }
10             }
11             alert(item);
12         }
13     </script>

主要是通过获取所选中项的前一个元素的属性valueCode,就是在后台代码中添加item的属性

以下是本文的效果图:


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM