-1

Ok guys here's my dilemma, I just need some basic help... soo

if I have a set of variable say...

$h1 = ""
$h2 = ""
$h3 = ""
$h4 = ""

and i'm using a data attribute on the element, how can I use the number I pull to put into a string that acts as the variable name. so in the function below, you click a class item, it get's the value from the data attribute then I need to populate the #work_hold div with the corresponding variable. If I do what I have below, the $tme acts as a string and doesnt work. any ideas?

$(".box").click(function(){
var atr = $(this).attr("data-bsel"); 
$tme = '$h'+atr;
$('#work_hold').html($tme);
  });
1

2 Answers 2

2

You want an array:

var h = [];
h[0] = ...;
h[1] = ...;
h[2] = ...;
...

$tme = h[atr];

You do NOT want to build variables dynamically. That just leads to utterly icomprehensible and impossible to debug code.

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

1 Comment

I like this answer best. Tackle how to use arrays before learning objects.
0

use javascript objects:

var nameSpace = {"$h1": 109};

$(".box").click(function(){
    var atr = $(this).attr("data-bsel"); 
    $tme = nameSpace['$h'+atr];
    $('#work_hold').html($tme);

});

2 Comments

the first one work but I'm definitely going to read about these objects cause they'll prob help me in the future. Thanks
developer.mozilla.org/en/JavaScript/Reference/Global_Objects/… here is a good example of objects in javascript

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.