Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    Regular Coder
    Join Date
    Nov 2002
    Posts
    672
    Thanks
    1
    Thanked 1 Time in 1 Post

    converting strings to variables

    Is it possible to convert a string to a variable? Well, here's one example with tables. In the function, X is a number passed on by an href or onClick event. You can't assign an ID as a numer though. So I tried giving each table an ID like t0, t1, t2, etc and
    just combine numbers from the event passed on to a t to form the ID and work with one function instead of one per table.

    function tab(X)
    {
    A="t"+X
    A.style.backgroundColor="blue"
    }

    But now A is a string. I can't pass t0 or t1 as an event becaues it's
    undefined.
    onMouseOver="tab(t0)"
    But if I put them in quotes in it
    onMouseOver="tab('t0')"
    it is also treated like a string and won't be recognized as anything when trying to get that to work as an ID. What can I do to fix this?

  • #2
    Senior Coder
    Join Date
    Jun 2002
    Location
    frankfurt, german banana republic
    Posts
    1,848
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Well, you use the function that's designed to access the HTML element as defined by it's Id value:

    document.getElementById("t"+ X).style.backgroundColor = 'Fnord';

  • #3
    Senior Coder
    Join Date
    Jun 2002
    Location
    Wichita
    Posts
    3,880
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Code:
    function tab(X) 
    { 
    A=document.getElementById("t"+X)
    A.style.backgroundColor="blue" 
    }
    This should work or even shorter:

    Code:
    function tab(X) 
    { 
    document.getElementById("t"+X).style.backgroundColor="blue" 
    }

  • #4
    Regular Coder
    Join Date
    Nov 2002
    Posts
    672
    Thanks
    1
    Thanked 1 Time in 1 Post
    Thanks, that is really useful. I try to keep my scripts as compact as possible, but sometimes after a week of not working on something, even I forget my logic. I should really start commenting my lines.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •