c# - CheckboxList 未在 JavaScript 中获取选定值

标签 c# javascript asp.net .net visual-studio-2010

我在 ASP.NET 中有复选框列表:

<asp:CheckBoxList ID="chbUserType" RepeatDirection="Horizontal" runat="server">
                    </asp:CheckBoxList>

我将其绑定(bind)为:

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>

最佳答案

我认为,如果您在输入中使用 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;
        }
    }
}

关于c# - CheckboxList 未在 JavaScript 中获取选定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23516263/

相关文章:

c# - 如果不为空,检查查询字符串参数值的最优雅方法?

c# - ASP.NET Core 运行两个 TestServer 进行集成测试

c# - 使用 System.Windows.Forms 损坏的 Mono C# 代码

c# - Microsoft.Management.Infrastructure 命名空间 - Cim 类

javascript - 使用 Angular-JS ng-disabled

javascript - Rails 中的 HAML link_to 不会在页面加载时应用类

c# - 一个解决方案中包含多个 Azure 云服务

javascript - 从进行 http 调用的方法返回 promise 的正确方法 (Angular2)

c# - 使用新文件更新文件

c# - DataTable.Select() 属性 : Giving Index Out of Bound Exception