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);
var indices = '';
$('#<%=chkListGroups.ClientID %> input:checkbox').each(function (index) {
if ($(this).filter('input:checkbox:checked').length == 1) {
indices += (index + ' ');
}
});
alert(indices);
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
indices += (valueArray[index] + ' ');
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:
var text = $('#<%=chkListGroups.ClientID %> input:checkbox:checked').siblings('label').text();
alert(text);