How to get the index of selected ASP.NET CheckBoxList items and the text value of it using jQuery
I used the code listed but it did not work with me.
First two lines will return message with "undefined" string
var index = $('#<%=chkListGroups.ClientID %>').attr("selectedIndex");
alert(index);
second two lines will return empty message.
var text = $('#<%=chkListGroups.ClientID %>').val();
alert(text);
should print the indices.
If by "text value" you mean what would be returned from the Value property of the ListItem element within ASP.NET, it is not directly included in the web page automatically. One way to address this issue would be to create a javascript array of the Value properties within the .NET code for the page, then use something similar to the above to look up the value in the array. If the array is called "valueArray", then you would could replace the code in the body of the "if" above with
I hope this helps -- I certainly welcome any questions.
EDIT (following comment by submitter):
If you want the visible label of each checked item, this should work:
Edit: mis-read your original question - updating this answer accordingly.
ASP.NET renders the checkBoxList control to be a series of checkboxes (you can use firebug to easily see the rendered controls). I believe it assigns the ID of each checkbox, based on the ID you specified. For example:
Is rendered in HTML as:
You can determine if a box is checked via:
You can also find them all via:
... then use jQuery iteration to scan through all checkboxes. I suspect jQuery can also be used to find the next "label" control after a target checkbox control, and extract the actual text from it. One of stackoverflow's bigger jQuery brains will have to help with with the exact selector syntax - I'm relatively new to jQuery, and don't know it off the top of my head.
Original response (applies to simple selectionLists):
This should get the selected index:
This should get the selected value: