In this recipe, we will retrieve the selected items of an ASP.NET CheckBoxList.
Create a new form
Recipe5.aspx
in the current project. Add a CheckBoxList control to the form. Also add a div area to display the selected items of the CheckBoxList at runtime:<form id="form1" runat="server"> <div align="left"> <fieldset style="width:400px;height:150px;"> <p>Different types of packages available:</p> <asp:CheckBoxList ID="CheckBoxList1" runat="server"> <asp:ListItem Text="Standard" Value="1"></asp:ListItem> <asp:ListItem Text="Silver" Value="2"></asp:ListItem> <asp:ListItem Text="Gold" Value="3"></asp:ListItem> <asp:ListItem Text="Premier" Value="4"></asp:ListItem> </asp:CheckBoxList> </fieldset> <br /> <div id="message"></div> </div> </form>
The page will display the CheckBoxList as shown below:
In the
document.ready()
function, define the click function of the CheckBoxList:$('#<%=CheckBoxList1.ClientID%>').click(function() {
Create a local string variable and initialize to an empty string:
var str = "";
Apply a jQuery selector to retrieve the checked boxes and apply the
each
function to each element returned:$('#<%=CheckBoxList1.ClientID%> input[type=checkbox]:checked').each(function() {
Retrieve the text of the selected CheckBox and append to the local string:
str = str + " " + $(this).next().text();
Note
Each of the checkbox elements is rendered as a
<input type="checkbox">
and<label>
pair. The label holds the text of the element. Hence, when retrieving the description of the element, we have used$(this).next().text()
, where$(this)
refers to the current checkbox element andnext()
refers to the consecutive<label>
element.After the execution of the
each()
function, display the local string in the div area'message'
:$('#message').text(str); });
The complete jQuery solution is as follows:
<script type="text/javascript"> $(document).ready(function() { $('#<%=CheckBoxList1.ClientID%>').click( function() { var str = ""; $('#<%=CheckBoxList1.ClientID%> input[type=checkbox]:checked').each(function() { str = str + " " + $(this).next().text(); }); $('#message').text(str); }); }); </script>