Jump to content


Photo

Radio Validation with Javascript


  • Please log in to reply
1 reply to this topic

#1 pikemsu28

pikemsu28
  • Members
  • PipPipPip
  • Advanced Member
  • 164 posts

Posted 03 October 2006 - 06:40 PM

I have a page that dynamically displays radio buttons.  the javascript validition function that i currently use works great as long as their are more than one radio buttons.  i've searched many forums trying to find an answer to this and have found the beginnings of my answer.  The reason my function shows the error when only one radio button is populated is because the radio group is no longer an array.  Therefor my loop will not function properly. 

My question is:  How would i set up my function to check the array length and if that length is more than one do my normal function, else check a single radio button?

I'm very new to javascript so please be specific/detailed with your response.  Also, i would like a good tutorial on validation if you have any to suggest.

thanks,
Jason


function checkRadios()
{
var el = document.forms[0].elements;
for(var i = 0 ; i < el.length ; ++i)
{
if(el[i].type == "radio")
{
var radiogroup = el[el[i].name];
var itemchecked = false;
for(var j = 0 ; j < radiogroup.length ; ++j)
{
if(radiogroup[j].checked)
{
itemchecked = true;
break;
}
}
if(!itemchecked)
{
alert("Please make a selection");
if(el[i].focus)
el[i].focus();
return false;
}
}
}
return true;
}


#2 fenway

fenway
  • Staff Alumni
  • MySQL Si-Fu / PHP Resident Alien
  • 16,199 posts
  • LocationToronto, ON

Posted 03 October 2006 - 09:00 PM

Check ( el.length == null ) -- no array, no .length property.
Seriously... if people don't start reading this before posting, I'm going to consider not answering at all.




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users