Rocket
Rocket

Reputation: 1093

Jquery - reading value from dynamic var?

I've got this snippet of code..

var test_a = "<?php echo $a ?>"
console.log (test_a);

This shows 1.576.21422 which is correct.

But when I try the same here I don't get the result I was expecting.. I get the variable name.

I know in this test fieldData[0] = 'a'

    console.log ("test_" + fieldData[0])

Instead of showing 1.576.21422 I get test_a

Can someone point me in the right direction for this... Thanks

Upvotes: 1

Views: 54

Answers (1)

PeterKA
PeterKA

Reputation: 24638

As it is you're outputting a string concatenated with another string. Your goal is to turn the resulting string into a variable. You could make the variable a member of a particular object (or the window object) and access the value of that member using the notation object[ "key" ].

Warning -- Even though eval( .... ) would work, I would not advice you to use it.

This should work:

window.test_a = "<?php echo $a ?>";
//.....
console.log ( window[ "test_" + fieldData[0] ] );

To avoid cluttering the global scope, this would be the recommended way:

var myObject = { test_a: "<?php echo $a ?>" };
//.......
console.log ( myObject[ "test_" + fieldData[0] ] );

Upvotes: 2

Related Questions