Question

I have checkbox list in asp.net as:

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

I have binded it as:

chbUserType.DataSource = dtRoles;
        chbUserType.DataValueField = "idRole";
        chbUserType.DataTextField = "Title";
        chbUserType.DataBind();

        foreach (ListItem li in chbUserType.Items)
        {
            li.Attributes.Add("JSvalue", li.Value);
        }   

I want to get its selected values in javascript.

For that i have done as follows:

    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);

I am not getting anything in alert.

Please help me how can i achieve this???

Edit 2 :

Generated 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>
Was it helpful?

Solution

I think if you use the getElementsByTagName on your inputs instead of getElementsByName you'll be fine...

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;
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top