In this article I will explain with an example, how to validate RadioButtonList using JavaScript in ASP.Net.
Validating an ASP.Net RadioButtonList using JavaScript means, checking whether at-least one RadioButton inside the RadioButtonList is checked or not using JavaScript.
HTML Markup
The following HTML Markup consists of an ASP.Net RadioButtonList.
<asp:RadioButtonList ID="RadioButtonList1" 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>
Concept
The ASP.Net RadioButtonList control is rendered as an HTML Table with HTML RadioButtons as shown below.
Hence we will need to write a script which will loop through all the controls (RadioButtons) in the generated HTML table in order to validate it.
Next important point is that a RadioButtonList Item has two parts.
1. Text
2. Value
The Value part is available in the value attribute of the HTML RadioButton, while the Text part is available in the HTML Label element.
Validate RadioButtonList using JavaScript in ASP.Net
The following HTML Markup consists of an ASP.Net RadioButtonList and a Button.
The Button has been assigned an OnClientClick event handler, which makes a call to the Validate Javascript function.
Inside the Validate JavaScript function, first the reference of the RadioButtonList is determined and then all the RadioButtons inside the RadioButtonList are referenced.
Then a loop is executed over the referenced RadioButtons and each RadioButton is validated whether it is checked or not.
If none of the RadioButtons is checked, then a JavaScript Alert Message Box is displayed with a message informing the user, that he has to select a RadioButton from the ASP.Net RadioButtonList.
<script type="text/javascript">
function Validate() {
var rb = document.getElementById("<%=RadioButtonList1.ClientID%>");
var radio = rb.getElementsByTagName("input");
var isChecked = false;
for (var i = 0; i < radio.length; i++) {
if (radio[i].checked) {
isChecked = true;
break;
}
}
if (!isChecked) {
alert("Please select an option!");
}
return isChecked;
}
</script>
<asp:RadioButtonList ID="RadioButtonList1" 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="btnSubmit" runat="server" Text="Validate" OnClientClick="return Validate()" />
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