How To Get The Index Of Selected Asp.net CheckBoxList Items And The Text Value Of It Using Jquery
Solution 1:
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);
Solution 2:
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:
<asp:CheckBoxList id="list1" runat="server">
<asp:ListItem>One</asp:ListItem>
<asp:ListItem>Two</asp:ListItem>
<asp:ListItem>Three</asp:ListItem>
</asp:CheckBoxList>
Is rendered in HTML as:
<table id="list1">
<tr><td><input id="list1_0" type="checkbox" /><label for="list1_0">One</label></td></tr>
<tr><td><input id="list1_1" type="checkbox" /><label for="list1_1">Two</label></td></tr>
<tr><td><input id="list1_2" type="checkbox" /><label for="list1_2">Three</label></td></tr>
</table>
You can determine if a box is checked via:
$('#list1_0').attr('checked')
You can also find them all via:
$('#list1 input')
... 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:
$("#SomeListID").attr("selectedIndex")
This should get the selected value:
$("#SomeListID").val()
Post a Comment for "How To Get The Index Of Selected Asp.net CheckBoxList Items And The Text Value Of It Using Jquery"