-1

I have a loop that checks the content of an element's data-attribute and then uses this content to match it in a switch function. I want to simplify this code because the data-attribute value may vary in the next future and every time I have to add a case to the switch. What I have now (this works fine):

var a = $('#el').attr('data-x'); // String
for (var i = 0; i <= 2; i++) {
    switch (a) {
        case "abc":
            abc++; // variable initially set to 0
            $('#abc').text(abc); // Overwrite the content with the new value
            break;
        case "dfg":
            dfg++;
            $('#dfg').text(dfg);
            break;
[ ...Many cases like the ones listed here ]
            }
if (i === 0) { a = $('#el').attr('data-x1')} 
else if (i === 1) { a = $('#el').attr('data-x2');} 
else if (i === 2) { a = $('#el').attr('data-x3');}
}

What I want to achieve is take the 'a' value, use the value taken as a var name and then work on the variable content.

EDIT: Mostly my need is a function non-depending from the cases, the way I've used in the code above it's ok for now but every 2 months I have to add another case to make it work. The question is: how can I change my code above to make it more "universal" and "elegant" in less line of code?

Something like:

var a = $('#el').attr('data-x');
for (var i = 0; i <= 2; i++) {
     a++; // 'a' must be the name of the var, the name of the variable it's the same as $('#el').attr('data-x').
          // So, 'a' var will change every time the function it's executed as in the switch version of the first block of code above (abc++ or dfg++).
     $('#'+a).text(a);
if (i === 0) { a = $('#el').attr('data-x1')} 
else if (i === 1) { a = $('#el').attr('data-x2');} 
else if (i === 2) { a = $('#el').attr('data-x3');}
}

Here lies my problem: 'a' will be a string ('abc' for example), abc is a global var with the number needed to be incremented and placed in $('#abc'). Here we have for example:

abc = 0; (global var)
a = abc; (scoped var)
abc++; (abc === 1)
$('#abc').text(abc); (equivalent to $('#abc').text(1);)

So I need to call in the loop the 'a' value as the name of the global var, increment it, and then use 'a' as a jquery selector to text the value of the incremented global var inside it. How can I do that?

1 Answers1

1

If I understand what you need to do, you should try to use eval()

The eval() function evaluates JavaScript code represented as a string.

var a = $('#el').attr('data-x');
for (var i = 0; i <= 2; i++) {
    eval(a + "++");
    $('#'+a).text(eval(a));
    if (i === 0) { a = $('#el').attr('data-x1')} 
    else if (i === 1) { a = $('#el').attr('data-x2');} 
    else if (i === 2) { a = $('#el').attr('data-x3');}
}
Rohit Agrawal
  • 1,496
  • 9
  • 20
Andrea Carron
  • 1,001
  • 13
  • 22