...

View Full Version : Help with radio button validation



Eclipse000
09-22-2011, 10:02 PM
Hi everyone. I'm getting into javascript coding and i'm stumped with some problem about radio buttons. What I would like is to have a general function where I can pass in any group of radio buttons and have it return the textual value of the radio button selected. First, here is my code so far.



function Get_Radio_Selection(options)
{
var choice = "";

for (var index = 0; index <= options.length; index++)
if (options[index].checked == true)
choice = options[index].value;

return choice;
}


Now here's a sample form:



<form name="form1">
<input type="radio" name="food" value="Banana">Banana
<input type="radio" name="food" value="Mango">Mango
<input type="radio" name="food" value="Orange">Orange
<input type="radio" name="food" value="Oatmeal">Oatmeal

<input type="button" name="blah" value="Get Selection"
onclick="Get_Radio_Selection(document.form1.food);">
</form>


My question is, when i run this function and pass it in the group of radio buttons by means of the onclick event handler, firefox 3.6.22 reports in the error console on line 22 that "options[index] is undefined". It seems that if i use the variable "index" more than one time it reports this error but if I take out the assignment to variable "choice" that it works just fine. I rewrote the function using a separate variable and this time it works perfectly:



function Get_Radio_Selection(options)
{
var choice = "";
var index;

for (var i = 0; i < options.length; i++)
{
if (options[i].checked == true)
{
index = i;

choice = options[index].value;
}
}

return choice;
}


Notice the indexing variables in the "if" statement and the assignment to "choice" are different. Does anyone have any suggestions on why this happens? Thanks.

Old Pedant
09-22-2011, 11:15 PM
I dunno why FF gives you the error. Looks like it is a scope of variable issue.
Bet it would work if you did

function Get_Radio_Selection(options)
{
var choice = "";

for (var index = 0; index <= options.length; index++)
{
if (options[index].checked == true)
{
choice = options[index].value;
}
}
return choice;
}

But why make the code so complex in the first place?


function Get_Radio_Selection(options)
{
for (var index = 0; index <= options.length; index++)
{
if (options[index].checked) return options[index].value;
}
return null;
}

As a minor precaution: That code will give an error if you ever have a group of radio buttons that actually has only one button in it!

Easy fix:


function Get_Radio_Selection(options)
{
// protect against single radio button
if ( options.length == null ) return options.checked ? options.value : null;

for (var index = 0; index <= options.length; index++)
{
if (options[index].checked) return options[index].value;
}
return null;
}



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum