Javascript validator for group of radio button

After spending long time on Google for getting decent javascript for checking radio button for more then one group selected or not.  I came up with this script which check whether radio button is selected or not and give warning message for selecting radio button.

Javascript

 function check(e){
for(var i=0;i<e.length;i++){
if(e[i].type=='radio'){
  var r=e[e[i].name],
  q=true
  for(var j=0;j<r.length;j++){
   if(r[j].checked){
     q=false;}
  else{
    p=r[j].name}}
if(q){alert('Please select an option in '+p+' radio group'  );return false} } } }

HTML

 <form name="myform" onsubmit="return check(this.elements)">
   <input type="radio" name="group1" value="value1"/>
   <input type="radio" name="group1" value="value2"/>
   <input type="radio" name="group1" value="value3"/>

   <input type="radio" name="group2" value="value1"/>
   <input type="radio" name="group2" value="value2"/>
   <input type="radio" name="group2" value="value3"/>

   <input type="radio" name="group3" value="value1"/>
   <input type="radio" name="group3" value="value2"/>
   <input type="radio" name="group3" value="value3"/>

 <input type="submit" />
</form>

There is always chance for improvement so please comment !

Share

Leave a Reply

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