How to use a variable as a part of an object

Discussion in 'Javascript' started by Stefan Mueller, Nov 30, 2005.

  1. 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
    Stefan Mueller, Nov 30, 2005
    #1
    1. Advertising

  2. Stefan Mueller

    VK Guest

    Stefan Mueller wrote:
    > 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
    VK, Nov 30, 2005
    #2
    1. Advertising

  3. Stefan Mueller

    RobG Guest

    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
    RobG, Nov 30, 2005
    #3
  4. That's perfect.

    Many thanks
    Stefan
    Stefan Mueller, Nov 30, 2005
    #4
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Bobby Chamness
    Replies:
    2
    Views:
    2,377
    Joe Smith
    Apr 22, 2007
  2. mfglinux
    Replies:
    11
    Views:
    681
    Roberto Bonvallet
    Sep 12, 2007
  3. Jack
    Replies:
    8
    Views:
    263
  4. cayenne
    Replies:
    19
    Views:
    649
    John W. Krahn
    May 20, 2004
  5. bing
    Replies:
    2
    Views:
    126
    Greg Bacon
    Aug 1, 2005
Loading...

Share This Page