0

I will trim this down to make it as simple as possible. I have a variable named car and another one named car_output. Let's say value = 'car' and car_output = 'I like to drive my car'

So, I'm trying to get the contents of car_output placed inside a div div#car:

$('#'+value).html(value+'_output');

This shows within the div div#car the actual word "car_output" and not what the variable's contents are (I like to drive my car).

How can I get the variable's contents to be placed inside div#car?

`

1
  • you can't do that.... what you can do is instead of creating variables create a key value pair and use bracket notation to fetch dynamic keys Commented Aug 6, 2014 at 5:27

2 Answers 2

2

To access a "dynamic" variable in javascript you can access it from the window object, like this:

val = "test";
test_output = "Testing completed";

out = window[val + "_output"];
alert(out);

this will echo "Testing completed"

Sign up to request clarification or add additional context in comments.

1 Comment

and the fiddle to test ==> jsfiddle.net/EF59p
0

this does it

$( '#' + value ).html( eval( value + '_output' ) );

Sample

var value      = 'car';
var car_output = 'I like to drive my car';

$( '#' + value ).html( eval( value + '_output' ) );

you just have to eval() your code before

see JSFIDDLE

1 Comment

Depending on how value is populated runing eval could be quite dangerous.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.