Click to See Complete Forum and Search --> : dynamic object references


modernlife
10-30-2003, 08:55 PM
Here's an interesting one:

Say you have a form with names go like this:

<input type="text" name="madonna_song_name">
<input type="text" name="britney_song_name">

<input type="text" name="madonna_age">
<input type="text" name="britney_age">

You might access the form objects like this:

document.form[0].madonna_song_name.value = "blah";
document.form[0].britney_age.disabled = true;

etc.

Now, let's say you were passing the value "madonna" to a function that is trying to disable/enable all the form inputs for that singer:

enable_disable( madonna );

function enable_disable( singer ) {
// singer == "madonna";
// go through form values:
// document.form[0].<singer>_song_name.disabled = true;
// document.form[0].<singer>_age.disbalbed = true;

}

My question is, how do you get the "<singer>" part to be dynamic? I tried things like:

testing = singer . "_song_name";
document.form[0].'testing'.disabled = true;

etc.

But I can't seem to get the syntax right.

Please point this sorry newb in the right direction, thanks! :)

Khalid Ali
10-30-2003, 09:42 PM
you are pretty close,eval function can be used here

eval('document.form[0].'+singerName+'.disabled = true');
where singer name should be replaced with the vriable

fredmv
10-30-2003, 09:50 PM
I would recommend against using eval as it uses more processing power and as a result isn't necessary to use when there are other options available.

I would suggest using the elements array of the form object. It would do the exact same thing, but the more correct way, and using less processing power. The function should be written like this:function enable_disable( name )
{
document.forms[0].elements[name].disabled = !document.forms[0].elements[name].disabled;
}I hope that helps you out.

modernlife
10-30-2003, 10:12 PM
Please correct me if I'm wrong, but doesn't using element[name] put me back where I started:

document.forms[0].elements[<singer>_age].disabled...

or is elements a numerically indexed array:

document.forms[0].elements[4].disabled...

?

Thanks to both of you for the help.

fredmv
10-30-2003, 10:19 PM
It should be as simple as this:document.forms[0].elements['singer_' + age].disabled = !document.forms[0].elements['singer_' + age].disabled;I hope that helps you out.