In this article I will explain with an example, how to validate Group of RadioButtons (Multiple RadioButtons) using JavaScript in ASP.Net.
When the Submit Button is clicked, all the RadioButtons in the Group will be referenced and using FOR loop, it will be validated that one RadioButton must be checked from the Group of RadioButtons using JavaScript in ASP.Net.
HTML Markup
The HTML Markup consist of an HTML Table with a Group of ASP.Net RadioButtons to be validated, an HTML SPAN for displaying the error message and an ASP.Net Button.
The ASP.Net Button has been assigned a JavaScript OnClick event handler.
<table id = "tblFruits" border="0" cellpadding="0" cellspacing="0">
<tr>
<td><asp:RadioButton ID="RadioButton1" Text="Mango" runat="server" GroupName = "Fruit" /></td>
</tr>
<tr>
<td><asp:RadioButton ID="RadioButton2" Text="Apple" runat="server" GroupName = "Fruit" /></td>
</tr>
<tr>
<td><asp:RadioButton ID="RadioButton3" Text="Banana" runat="server" GroupName = "Fruit" /></td>
</tr>
<tr>
<td><asp:RadioButton ID="RadioButton4" Text="Grapes" runat="server" GroupName = "Fruit" /></td>
</tr>
<tr>
<td><asp:RadioButton ID="RadioButton5" Text="Orange" runat="server" GroupName = "Fruit" /></td>
</tr>
</table>
<br />
<span id="spnError" class="error" style="display: none">Please select a Fruit.</span>
<br />
<asp:Button ID="Button1" Text="Submit" runat="server" OnClientClick = "return Validate()" />
JavaScript function to validate Group of RadioButtons (Multiple RadioButtons) in ASP.Net
When the Submit Button is clicked, all the RadioButtons inside the Table are referenced using the Tag Name.
Then using FOR loop, each RadioButton is verified whether it is checked.
If one RadioButton is checked, then the validation is successful else an error message is displayed using JavaScript.
<script type="text/javascript">
function Validate() {
//Reference the Table.
var radio = document.getElementById("tblFruits");
//Reference the Group of RadioButtons.
var radio = table.getElementsByTagName("INPUT");
//Set the Valid Flag to False initially.
var isValid = false;
//Loop and verify whether at-least one RadioButton is checked.
for (var i = 0; i < radio.length; i++) {
if (radio[i].checked) {
isValid = true;
break;
}
}
//Display error message if no RadioButton is checked.
document.getElementById("spnError").style.display = isValid ? "none" : "block";
return isValid;
}
</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