...

View Full Version : Resolved How do I use a string variable as a "name"?



bobleny
08-20-2011, 02:04 AM
I have this function:


function SelectedRadio(form, name)
{
for(var i = 0; i < form.name.length; i++)
{
if(form.name[i].checked == true)
{
return form.name[i].value;
}
}

return "Error!";
}


Form is a form object, and name is a string of the name of the radio button.

I thought it was trying to use the variable name as the name of a field. For example:


function OnFormSubmit(form)
{
SelectedRadio(form, "fruits")
}


Instead of form.fruits its using form.name. Basically I am trying to use the variable as a string.

Is there anyway around this?

Logic Ali
08-20-2011, 03:17 AM
form[ name ][ i ]

It would be better to pass a reference to the radio group:
function getRadioValue( group )
{
if( group.length )
for( var i = 0; i < group.length && !group[ i ].checked; i++ )
;

return group.length && i != group.length ? group[ i ].value : group.checked ? group.value : "" ;
}

bobleny
08-20-2011, 03:48 AM
It would be better to pass a reference to the radio group:


That's what I was doing because I couldn't figure out how to make it work the other way.


form[ name ][ i ]

Oh, but why no dot (.) between form and [name]?

devnull69
08-20-2011, 11:17 AM
You have a string as the name parameter. A string in javascript is represented by a sequence of characters surrounded by quotes.

This is a string


"fruits"


If you use form.name in that case it will become


from."fruits"

which will result in an error, whereas form[name] will give


form["fruits"]

which is perfectly legal.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum