We help IT Professionals succeed at work.

Create variable name with string value in JavaScript

treyjeff
treyjeff asked
on
4,588 Views
Last Modified: 2011-09-20
I have a bunch of custom fields but sometimes the index starts at a different number. So down below I'm trying to alert(myVariable);

So I want to take a string: myVariable and add another part of a string on "1" and be able to alert(myVariable1) and have it spit out the value of that variable.

I know there is a name for this but I can't recall it :( and PHP allows me to do it by adding {}.
Comment
Watch Question

Top Expert 2007
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION

Author

Commented:
Will try that right now...
Top Expert 2007

Commented:
Another example with a field, where "field1" is the name/id of an input field in the document's first form:

  var a = 'field';      
  alert( document.forms[0][a+1].value );
Hi,

<script type='text/javascript'>

function makeObj(str)
{
  window[str] = new Object();
  document.write(str + '<br />')
}

for (var i = 0; i < 10; i++)
makeObj('theObj'+i);
</script>
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.