Jump to content

Radio Validation with Javascript


pikemsu28

Recommended Posts

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;
}
Link to comment
https://forums.phpfreaks.com/topic/22900-radio-validation-with-javascript/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.