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 an ASP.Net CheckBoxList and a Button.
<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="return GetSelected()" />
Understanding the CheckBoxList on Client Side
The CheckBoxList is rendered as an HTML Table in 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 part while the Label element contains the Text part.
Get Selected Text and Value of ASP.Net CheckBoxList using Javascript
When the btnGet Button is clicked, the GetSelected JavaScript function is executed.
Inside this function, first the CheckBoxList is referenced and then all the CheckBoxes present inside the CheckBoxList are referenced.
Then a loop is executed over the referenced CheckBoxes and each CheckBox is checked whether it is selected or not.
If a CheckBox is selected, then its Value part is fetched from the value attribute and the Text part is fetched from the HTML content of the corresponding Label element.
Finally the Text and Value of the selected CheckBoxes are displayed using JavaScript Alert message box.
<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
Browser Compatibility
The above code has been tested in the following browsers.
* All browser logos displayed above are property of their respective owners.
Demo
Downloads