0

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>
1
  • Could you also provide a sample of the generated HTML? Commented May 7, 2014 at 11:26

1 Answer 1

2

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;
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.