In this article I will explain with an example, how to get
Text and
Value of selected CheckBox using
jQuery in ASP.Net.
HTML Markup
The HTML Markup consists of following controls:
CheckBoxList – For capturing user input.
The CheckBoxList consists of four ListItems in which Selected property of one ListItem is set to TRUE.
Button – For displaying Text and Value of checked CheckBoxes.
<asp:CheckBoxList ID="chkFruits" runat="server">
<asp:ListItem Text="Mango" Value="1" />
<asp:ListItem Text="Apple" Value="2" />
<asp:ListItem Text="Banana" Value="3" Selected="True" />
<asp:ListItem Text="Guava" Value="4" />
</asp:CheckBoxList>
<asp:Button ID="btnGet" runat="server" Text="Get Selected Items" />
Understanding the CheckBoxList on Client Side
The CheckBoxList is rendered as an HTML Table on client side browser. Each Item of CheckBoxList is a Table row consisting of a Table Cell with a CheckBox and a Label element.
The CheckBox holds the Value, while the Label element contains the Text.
Getting Text and Value of Selected CheckBoxes of ASP.Net CheckBoxList using jQuery
Inside the HTML Markup, the following script file is inherited.
1. jquery.min.js
Inside the document ready event handler, the
Get Selected Item Button has been assigned with a
jQuery click event handler.
When Get Selected Items Button is clicked, first the references of the checked CheckBoxes in the CheckBoxList are determined.
A FOR EACH loop is executed over all checked Items and the Value of checked CheckBoxes are fetched and Text of associated Label elements are also fetched.
Finally, the
Text and
Value of all the selected CheckBoxList Items are displayed using
JavaScript Alert Message Box and FALSE is returned.
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("[id*= btnGet]").click(function () {
var checked_checkboxes = $("[id*= chkFruits]input:checked");
var message = "";
checked_checkboxes.each(function () {
var value = $(this).val();
var text = $(this).closest("td").find("label").html();
message += "Text: " + text + " Value: " + value;
message += "\n";
});
alert(message);
return false;
});
});
</script>
Screenshot
Demo
Downloads