In this article I will explain with an example, how to implement ASP.Net RadioButtonList SelectedIndexChanged event in JavaScript.
The SelectedIndexChanged event is a Server Side event of ASP.Net RadioButtonList 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 RadioButtonList.
<asp:RadioButtonList ID="rblFruits" 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:RadioButtonList>
Understanding the RadioButtonList on Client Side
The RadioButtonList is rendered as an HTML Table in client side browser. Each item of RadioButtonList is a Table row consisting of a Table Cell with a RadioButton and a Label element.
The RadioButton holds the Value part while the Label element contains the Text part.
Get Selected Text and Value of ASP.Net RadioButtonList using JavaScript
Inside the JavaScript Window OnLoad event handler, the RadioButtonList is referenced and then the RadioButtons inside the RadioButtonLists are referenced.
Then a loop is executed over the RadioButtons and each RadioButton is assigned a JavaScript OnChange event handler.
Inside the JavaScript OnChange event handler, the RadioButton which is selected is referenced and then its corresponding Label element is referenced.
Finally the Text and Value of the selected RadioButton of the RadioButtonList is displayed using JavaScript Alert message box.
<script type="text/javascript">
window.onload = function () {
var rbl = document.getElementById("<%=rblFruits.ClientID %>");
var radio = rbl.getElementsByTagName("INPUT");
for (var i = 0; i < radio.length; i++) {
radio[i].onchange = function () {
var radio = this;
var label = radio.parentNode.getElementsByTagName("LABEL")[0];
alert("SelectedText: " + label.innerHTML
+ "\nSelectedValue: " + radio.value);
};
}
};
</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