In this article I will explain with an example, how to get selected (checked)
CheckBox Text and
Value from
CheckBoxList using
JavaScript 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.
The Button has been assigned with an OnClientClick event handler.
<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" Text="Get Selected Items" runat="server" OnClientClick="returnGetSelected()" />
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
When Get Selected Items Button is clicked, first the references of the CheckBoxList and each CheckBoxes inside it are determined.
A FOR EACH loop is executed over all the CheckBoxes and Value of all checked CheckBoxes is fetched and the 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">
function GetSelected() {
var message = "";
var checkBoxList = document.getElementById("<%=chkFruits.ClientID%>");
var checkBoxes = checkBoxList.getElementsByTagName("INPUT");
for (var i = 0; i < checkBoxes.length; i++) {
if (checkBoxes[i].checked) {
var value = checkBoxes[i].value;
var text = checkBoxes[i].parentNode.getElementsByTagName("LABEL")[0].innerHTML;
message += "Text: " + text + " Value: " + value;
message += "\n";
}
}
alert(message);
return false;
}
</script>
Screenshot
Demo
Downloads