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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.