Click to See Complete Forum and Search --> : tricky...how to use a varible in a function to form a variable name?


gilles007
05-10-2006, 11:49 PM
given a js function with an argument n ie:

myfunction(n)

Is there a way I can use n to refer to a form variable called item_1?

For example, in my function, I want to assign a value to a variable:
document.myform.myinput_1.value = "hello";

I really want the _1 above to be determined by n. That is if 2 is passed, I want:
document.myform.myinput_2.value = "hello";

Thanks for any help!

Gilles

Weedpacket
05-11-2006, 02:57 AM
var thisthing=42;

var thatthing= "thisthing";

alert(eval(thatthing));

gilles007
05-11-2006, 09:52 AM
Thanks for your suggestion but I 'm still stuck.

It's close though.

The tricky part is that the value of the variable that is passed to my function must be "part of" the final variable name I need to refer to. See my example above.

So how do I somehow make what is passed part of the final variable name I'm constructing?

Thanks,

GIlles

Weedpacket
05-12-2006, 08:04 AM
It's just string concatenation...

eval('document.myform.myinput_'+n+'.value = "hello"');

gilles007
05-12-2006, 10:10 AM
Of course!

Thanks for your help!

Gilles

JPnyc
05-12-2006, 12:22 PM
Javascript gives us a native object to deal with this. The elements object

document.myform.elements[i].value =

Then you just change the value of i and iterate through