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?

`

MultiDev
  • 10,389
  • 24
  • 81
  • 148
  • 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 – Arun P Johny Aug 06 '14 at 05:27

2 Answers2

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"

Philip G
  • 4,098
  • 2
  • 22
  • 41
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

Dwza
  • 6,494
  • 6
  • 41
  • 73