How to use a variable as a part of an object

S

Stefan Mueller

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
 
V

VK

Stefan said:
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
 
R

RobG

Stefan said:
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 >
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top