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