Multiple Radiobutton Validation by using Group-Name

Category: JAVA SCRIPT Comments: No comments

This is a simple way to validate a group of RadioButton in a page using Java Script.

  • If you want to validate multiple radio buttons categorised by their groupname attribute.
  • Lets assume there are 6 radio buttons belongs to 3 different groups.
  • Its a simple JS validation for multiple groups and u can show the error message also at a time those fileds which are not filled thats why a span tag is provided der.
  • Make sure that only group names  should be in the format as in this example likegroup1….group10 and span names like span1,span2….span15.

Paste the code in the Default.aspx

<form id=”form1″ runat=”server”>
<div>Your Gender :
<asp:RadioButton ID=”rbMale” runat=”server” GroupName=”group1″ Text=”Male”/>
<asp:RadioButton ID=”rbFemale” runat=”server” GroupName=”group1″ Text=”Female”/>
<span id=”span1″ runat=”server” style=”display:none;”>Select u r male or female.</span>

<div>Do u play Cricket ?
<asp:RadioButton ID=”rbYes” runat=”server” GroupName=”group2″ Text=”Yes”/>
<asp:RadioButton ID=”rbNo” runat=”server” GroupName=”group2″ Text=”No”/>
<span id=”span2″ runat=”server” style=”display:none;”>Select a yes or no.</span>

<div>Are u Vegeterian or u prefer Non Veg ?
<asp:RadioButton ID=”rbVeg” runat=”server” GroupName=”group3″ Text=”Vegiterian”/>
<asp:RadioButton ID=”rbNonveg” runat=”server” GroupName=”group3″ Text=”Non Veg”/>
<span id=”span3″ runat=”server” style=”display:none;”>Select a veg or nonveg.</span>

<asp:Button ID=”btnSubmit” runat=”server” Text=”Submit” OnClientClick=”return Validation(‘form1′)” />

Now with in the head paste the script code.

  • See there are more than one flags coz to display all the validation errors at a time .
  • var totalNoGroups is there u just provide the no of groups you use.

<script type=”text/javascript”>
function Validation(objForm) {
//There are 3 groups so take 3 flags.
var flag1 = false;
var flag2 = false;
var flag3 = false;
var totalNoGroups = 3;

for (var i = 1; i <= totalNoGroups; i++) {
var ans = form1["group" + i];
var checked = false;
var flag = “flag” + i;
var span = “span” + i;
for (var j = 0; j < ans.length; j++) {
if (ans[j].checked) {
document.getElementById(span).style.display = “none”;
flag = true;
else {
if (j == ans.length – 1) {
document.getElementById(span).style.display = “block”;

if (flag1 == true && flag2 == true && flag3 == true) {
return true;
else {
return false;

Leave a Reply

Your email address will not be published. Required fields are marked *


HTML tags are not allowed.