In this article I will explain with an example, how to use
JavaScript with RadioButtonList control in ASP.Net.
This article will explain how to validate RadioButtonList to find whether an item is selected or not and also how to get the selected
Text and
Value of the RadioButtonList using
JavaScript in ASP.Net.
HTML Markup
The following HTML Markup consists of:
RadioButtonList – For displaying RadioButtons.
The RadioButtonList consists of three ListItems.
Button – For validating and displaying Text and Value of selected RadioButton.
The Button has been assigned with an
OnClientClick event handler for calling the
Validate JavaScript function.
<asp:RadioButtonList ID="rblNumbers" runat="server">
<asp:ListItem Text="One" Value="1"></asp:ListItem>
<asp:ListItem Text="Two" Value="2"></asp:ListItem>
<asp:ListItem Text="Three" Value="3"></asp:ListItem>
</asp:RadioButtonList>
<br />
<asp:Button ID="btnValidate" runat="server" Text="Validate" OnClientClick="return Validate()" />
Validating RadioButtonList and Displaying Text and Value of the selected RadioButton using JavaScript
When Validate button is clicked, the RadioButtonList, RadioButtons and Label elements are referenced.
Then, a FOR loop is executed and check is performed whether the RadioButton is checked or not if it is checked then, its
Text and
Value is fetched and displayed using
JavaScript alert Message Box.
A check is performed if none of the RadioButton is checked, then a
JavaScript Alert Message Box is displayed with appropriate message.
Finally, the isCheck variable is returned.
<script type="text/javascript">
function Validate() {
var radioButtonList = document.getElementById("<%=rblNumbers.ClientID%>");
var radioButtons = radioButtonList.getElementsByTagName("input");
var label = radioButtonList.getElementsByTagName("label");
var isChecked = false;
var message = "";
for (var i = 0; i < radioButtons.length; i++) {
if (radioButtons[i].checked) {
isChecked = true;
message += "SelectedValue: " + radioButtons[i].value;
message += "\nSelectedText: " + label[i].innerHTML;
break;
}
}
if (!isChecked) {
alert("Please select an option!");
} else {
alert(message);
}
return isChecked;
}
</script>
Screenshot
Browser Compatibility
* All browser logos displayed above are property of their respective owners.
Demo
Download