6

So here is what I am trying to do:

  1. My variable named data_1 is set.

    var data_1 = {
      "y_legend": {
        "text": "# of Patients",
        "style": "{font-size: 20px; color: #778877}"
      },
      "x_legend": {
        "text": "AUG 09 - OCT 09",
        "style": "{font-size: 20px; color: #778877}"
      }
    };
    
  2. In a drop down a user selects an option with the value of data_1 that calls load('data_1').

    function load(data)
    {
      tmp = findSWF("my_chart");
      x = tmp.load( JSON.stringify(data) );
    }
    

My Problem: I'm selecting an option with the value data_1 and not the variable itself. So in my function load('data_1'), when I alert(data) I get data = 'data_1'.

So how do I get the contents of my variable data_1 in my load function by passing only the name of the string?

Jason Plank
  • 2,336
  • 5
  • 31
  • 40
Fostah
  • 2,947
  • 4
  • 56
  • 78

3 Answers3

7
var data_1 = { /* data goes here */ };

var data_choices = {1: data_1, 2: data_2, /* and so on */};

var load = function (data) {
    // data is "1", "2", etc. If you want to use the full data_1 name, change
    // the data_choices object keys.

    var tmp = findSWF("my_chart");
    var x = tmp.load( JSON.stringify(data_choices[data]) );
}
John Millikin
  • 197,344
  • 39
  • 212
  • 226
5

If it's a global variable, you can reference it with

window['the_variable_name']

E.g.

function load(data)
{ 
  tmp = findSWF( "my_chart" ); 
  x = tmp.load( JSON.stringify( window[data] ) ); 
}
jimr
  • 11,080
  • 1
  • 33
  • 32
3

or you could simply use

alert(eval(data)) 
Lil'Monkey
  • 991
  • 6
  • 14
  • 1
    Whoah! You have to be REALLY CAREFUL when using eval()! http://stackoverflow.com/questions/86513/why-is-using-javascript-eval-function-a-bad-idea – Matt Ball Sep 02 '09 at 18:38
  • 2
    as stated in the second answer in the post u linked : eval isn't always evil. There are times where it's perfectly appropriate. – Lil'Monkey Sep 02 '09 at 18:52
  • @Matt Ball Not agree to give -1 to this answer because suggest to use Eval. Eval could be use carrefully, but could be practice to be use for debug. – Cédric Boivin Sep 02 '09 at 18:58