我在asp.net中有一个复选框列表:
<asp:CheckBoxList ID="chbUserType" RepeatDirection="Horizontal" runat="server">
</asp:CheckBoxList>
我把它绑定为:
chbUserType.DataSource = dtRoles;
chbUserType.DataValueField = "idRole";
chbUserType.DataTextField = "Title";
chbUserType.DataBind();
foreach (ListItem li in chbUserType.Items)
{
li.Attributes.Add("JSvalue", li.Value);
}
我想在javascript中获取其选定的值。
为此,我做了如下:
var userType = "";
var chkBox = document.getElementById('<%=chbUserType.ClientID %>');
var options = chkBox.getElementsByName('input');
var listOfSpans = chkBox.getElementsByTagName('span');
for (var i = 0; i < options.length; i++) {
if (options[i].checked) {
if (i != options.length - 1) {
userType = listOfSpans[i].attributes["JSvalue"].value + ",";
}
else {
userType = listOfSpans[i].attributes["JSvalue"].value;
}
}
}
alert(userType);
我没有得到任何警觉。
请帮助我如何实现这一目标?
编辑2:
生成的HTML
<span jsvalue="2"><input id="MainContent_chbUserType_1" type="checkbox" name="ctl00$MainContent$chbUserType$1" value="2"><label for="MainContent_chbUserType_1">Dispatcher</label></span>
答案 0 :(得分:2)
我认为如果您在输入中使用getElementsByTagName
而不是getElementsByName
,那么您就可以了......
Here is a jsfiddle link that I think represents your problem
var userType = "";
var chkBox = document.getElementById('checkboxlist');
var options = chkBox.getElementsByTagName('input');
var listOfSpans = chkBox.getElementsByTagName('span');
for (var i = 0; i < options.length; i++) {
console.log(options[i].checked);
if (options[i].checked) {
if (i != options.length - 1) {
userType = listOfSpans[i].attributes["JSvalue"].value + ",";
}
else {
userType = listOfSpans[i].attributes["JSvalue"].value;
}
}
}