In this article I will explain with an example, how to implement ASP.Net CheckBoxList SelectedIndexChanged event in JavaScript.
The SelectedIndexChanged event is a Server Side event of ASP.Net CheckBoxList and in JavaScript which is Client Side programming language, OnChange event handler is being used.
HTML Markup
The HTML Markup consists of an ASP.Net CheckBoxList.
<asp:CheckBoxList ID="chkFruits" runat="server">
<asp:ListItem Text="Mango" Value="1"></asp:ListItem>
<asp:ListItem Text="Orange" Value="2"></asp:ListItem>
<asp:ListItem Text="Banana" Value="3"></asp:ListItem>
<asp:ListItem Text="Apple" Value="4"></asp:ListItem>
<asp:ListItem Text="Papaya" Value="5"></asp:ListItem>
</asp:CheckBoxList>
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
Inside the JavaScript Window OnLoad event handler, the CheckBoxList is referenced and then the CheckBoxes inside the CheckBoxLists are referenced.
Then a loop is executed over the CheckBoxes and each CheckBox is assigned a JavaScript OnChange event handler.
Inside the JavaScript OnChange event handler, the CheckBox which is selected is referenced and then its corresponding Label element is referenced.
Finally the Text and Value of the selected CheckBox of the CheckBoxList is displayed using JavaScript Alert message box.
<script type="text/javascript">
window.onload = function () {
var chk = document.getElementById("<%=chkFruits.ClientID %>");
var checkboxes = chk.getElementsByTagName("INPUT");
for (var i = 0; i < checkboxes.length; i++) {
checkboxes[i].onchange = function () {
var message = "";
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
var label = checkboxes[i].parentNode.getElementsByTagName("LABEL")[0];
message += "Value: " + checkboxes[i].value +
" Text: " + label.innerHTML + "\n";
}
}
alert(message);
};
}
};
</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