View Full Version : Does javascript have variable variables?

06-11-2004, 10:32 AM
My form has a slew of text inputs and they are named as below:

item1 total_item1
item2 total_item2
item3 total_item3
... (ad infinitum)

with total_itemX = itemX * 5 (where X is a number)

I've managed a script that looops through all the elements and grabs the user inputs from the items, but I haven't figured out how to output to the total_items yet. This is what I have so far:

// Run through all the form fields
for (var i=0; i < frm.elements.length; ++i) {
form_field = frm.elements[i] // Get the current field
form_name = form_field.name // Get the field's name
if (form_name.substring(0,4) == "item") { // Is it an "item" field?
item_price = 5;
item_quantity = parseInt(form_field.value) // Get the quantity

var foo = 'total_' + form_name;
frm.foo.value = item_quantity * item_price;

The last two lines of script patently don't work. I want to output to an element who's name is in the variable 'foo', not the element called 'foo'. I'd really appreciate if someone could point me in the right direction.

06-11-2004, 10:41 AM
frm.elements[foo].value = item_quantity * item_price;

Read more about the bracket notation (http://www.litotes.demon.co.uk/js_info/sq_brackets.html)

06-11-2004, 10:53 AM
Thank you! I can't believe I missed that >.<