Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
Home
Discussion GroupsGeneralPHPASPPerlColdFusionFlashHTML, CSS, ScriptsBrowsers

Webmaster Forum / HTML, CSS, Scripts / JavaScript / November 2005



Tip: Looking for answers? Try searching our database.

How to use a variable as a part of an object

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
Stefan Mueller - 30 Nov 2005 20:33 GMT
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";

Stefan
VK - 30 Nov 2005 20:45 GMT
> 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";

document.forms["MyForm"].elements[MyVariable].value = "Test";
// MyVariable goes without quotes of course
RobG - 30 Nov 2005 21:00 GMT
> To change the value of input boxes I use
>   document.MyForm.MyInput1.value = "Test";
[quoted text clipped - 4 lines]
>   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 >

Signature

Rob

Stefan Mueller - 30 Nov 2005 22:23 GMT
That's perfect.

Many thanks
Stefan
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2009 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.