ASPNET中如何使用JavaScript获取CheckBoxList的值?实例解析。
- 行业动态
- 2025-03-02
- 1
在ASP.NET中,可以使用JavaScript来获取CheckBoxList中的选中值。以下是一个示例代码:“
javascript,function getSelectedValues() {, var selectedValues = [];, var checkBoxList = document.getElementById('');, for (var i = 0; i``这个函数会返回一个包含所有选中值的数组。
在ASP.NET中,通过JavaScript获取CheckBoxList
控件中选中的值是一个常见的需求,由于CheckBoxList
在客户端生成的HTML结构较为复杂,直接通过JavaScript操作可能会遇到一些困难,以下是几种实现方法的详细实例:
通用版本(不依赖任何类库)
这种方法适用于RepeatLayout
属性为Flow
或Table
,RepeatDirection
属性为Horizontal
或Vertical
的情况。
function GetCheckBoxListValue(objID) { var v = new Array(); var CheckBoxList = document.getElementById(objID); if (CheckBoxList.tagName == "TABLE") { for (i = 0; i < CheckBoxList.rows.length; i++) { for (j = 0; j < CheckBoxList.rows[i].cells.length; j++) { if (CheckBoxList.rows[i].cells[j].childNodes[0]) { if (CheckBoxList.rows[i].cells[j].childNodes[0].checked == true) { v.push(CheckBoxList.rows[i].cells[j].childNodes[1].innerText); } } } } } if (CheckBoxList.tagName == "SPAN") { for (i = 0; i < CheckBoxList.childNodes.length; i++) { if (CheckBoxList.childNodes[i].tagName == "INPUT") { if (CheckBoxList.childNodes[i].checked == true) { i++; v.push(CheckBoxList.childNodes[i].innerText); } } } } return v; }
Asp.net Ajax版本(依赖Asp.net Ajax类库支持)
如果项目中使用了Asp.net Ajax类库,可以使用以下方法:
function GetCheckBoxListValue(objID) { var v = new Array(); var CheckBoxList = $get(objID); if (CheckBoxList.tagName == "TABLE") { for (i = 0; i < CheckBoxList.rows.length; i++) { for (j = 0; j < CheckBoxList.rows[i].cells.length; j++) { if (CheckBoxList.rows[i].cells[j].childNodes[0]) { if (CheckBoxList.rows[i].cells[j].childNodes[0].checked == true) { Array.add(v, CheckBoxList.rows[i].cells[j].childNodes[1].innerText); } } } } } if (CheckBoxList.tagName == "SPAN") { for (i = 0; i < CheckBoxList.childNodes.length; i++) { if (CheckBoxList.childNodes[i].tagName == "INPUT") { if (CheckBoxList.childNodes[i].checked == true) { i++; Array.add(v, CheckBoxList.childNodes[i].innerText); } } } } return v; }
使用自定义属性保存值的方法
由于默认情况下,CheckBoxList
生成的每个checkbox上不存在value值,可以通过后台代码为每个ListItem
添加自定义属性来保存Value值。
后台C#代码
foreach (DataRow row in dt.Rows) { ListItem li = new ListItem(); li.Text = row["Description"].ToString(); li.Value = row["Code"].ToString(); li.Attributes.Add("myValue", row["Code"].ToString()); cbl.Items.Add(li); }
JavaScript代码
function GetCheckBoxListValue(objID) { var v = new Array(); var CheckBoxList = document.getElementById(objID); if (CheckBoxList.tagName == "SPAN") { for (i = 0; i < CheckBoxList.childNodes.length; i++) { if (CheckBoxList.childNodes[i].tagName == "INPUT") { if (CheckBoxList.childNodes[i].checked == true) { i++; v.push(CheckBoxList.childNodes[i].getAttribute("myValue")); } } } } return v; }
三种方法分别展示了如何在ASP.NET中使用JavaScript获取CheckBoxList
控件中选中的值,根据项目的实际情况和需求,可以选择最适合的方法来实现这一功能。