Using array values as arrays themselves
The Problem
I have an issue where I need to get a value out of an array, and then use that value as an array itself to retrieve another value. Here's a little example.
Basically, I have an array of the form,
var animals = new Array("cats","dogs");
I have a form that has radio options, and let's pretend that one radio name is cats, as in
<input type="radio" name="cats" value="siamese" /> <input type="radio" name="cats" value="tiger" />
In my application, I only have two values for each radio name, so I reference them with,
document.getElementById('form').cats[0].value
and
document.getElementById('form').cats[1].value
or
document.getElementById('form').dogs[0].value
and
document.getElementById('form').dogs[1].value
What I'm wanting to do is use the animals array above to get the value, as in
document.getElementById('form').animals[0][0].value
which is wrong.
This previous line should really be document.getElementById('form').cats[0].value where animals[0] was replaced by cats.
That above should equal siamese, and document.getElementById('form').animals[0][1].value should equal tiger.
The Solution
Instead of using the dot notation, try the array index notation instead. So instead of element.name you will be using element[name].
document.getElementById('form')[animals[0]][0].value
So, document.getElementById('form')[animals[0]][0].value equals siamese.
Thanks pmw57 » for the help.
[Click to add or edit comments])
Please prepend comments below including a date