Re: How to use a variable as a part of an object
Available news archives: comp.lang.tcl - comp.lang.python - comp.security.firewalls - sci.crypt - comp.lang.php - comp.lang.javascript
Google
 
Web news.hping.org


comp.lang.javascript archive

Re: How to use a variable as a part of an object

From: RobG <rgqld@iinet.net.au>
Date: Wed Nov 30 2005 - 22:00:29 CET

Stefan Mueller wrote:
> To change the value of input boxes I use
> document.MyForm.MyInput1.value = "Test";
> document.MyForm.MyInput2.value = "Test";
>
> Is it also possible to use a variable instead of MyInput1 and MyInput2?
> I'm thinking about something like
> var MyVariable = "MyInput1";
> document.MyForm.MyVariable.value = "Test";

Yes:

   document.MyForm.elements[MyVariable].value = "Test";

or

   document.MyForm[MyVariable].value = "Test";

I prefer the former as it is clear that MyVariable refers to the form's
elements collection. Others prefer the later.

They are equivalent to:

   document.MyForm.elements["MyInput1"].value = "Test";

When you use dot notation, the script engine looks for a property with
that name. When you use square brackets, the engine expects an
expression that when evaluated will give a string that can be used for
the name.

It's covered in more detail in the FAQ:

   <URL: http://www.jibbering.com/faq/faq_notes/square_brackets.html >

-- 
Rob
Received on Sat Dec 3 04:34:00 2005