5

I have 2 variables like so

var variable_1 = "foo";
var variable_2 = "bar";

I use a function to grab the value of a checkbox input and for each checkbox which is checked, I want to load the particular variable which depends on value of checkbox.

$("input:checked").each(function() {
    $(div).append('variable_'+$(this).val());
}

So I'd concatenate the text 'variable_' with the value of each checkbox.

Thanks!

Andriy Ivaneyko
  • 15,838
  • 3
  • 43
  • 65
Matt Pierce
  • 641
  • 15
  • 35
  • If the variables are global, use `window['variable_' + $(this).val()]` – Tushar Mar 16 '16 at 05:59
  • 3
    You'd better use object to store values `var values = {variable_1='foo', ...}` and access its properties by name `$(div).append(values['variable_' + $(this).val()])` – Yury Tarabanko Mar 16 '16 at 06:03
  • You can use `eval` to get value of any variable dynamically. like `$(div).append(eval("variable_" + $(this).val()))` – Ranish Karim Mar 16 '16 at 06:57

4 Answers4

1

You can use eval to get any variable values dynamically.

var variable_1 = "foo";
var variable_2 = "bar";

$("input:checked").each(function() { $(div).append(eval('variable_'+$(this).val())); }

Note: it's not the best solution because eval has some security issues as well.

Ranish Karim
  • 366
  • 1
  • 8
  • eval is a very dangerous bit of code tho. – Tim Ogilvy Mar 16 '16 at 07:02
  • Yes, you are right `eval` has some security issues. But if he don't want to use object to save variable values or `window` to get variable value dynamically then I think eval is the last option he can do to get value dynamically – Ranish Karim Mar 16 '16 at 07:07
0

Create object with properties and access that properties via obj['prop'] notation, see code below:

var myObj = {'variable_1': 'foo', 'variable_2': 'bar'};
 $("input:checked").each(function() {
    var dynamicVariableName = 'variable_' + $(this).val()
    var dynamicVarValue = myObj[dynamicVariableName];
    $(div).append(dynamicVar);
}

If your variables lives under window it's better to create new global object which contains that variable rather than keeping that variables as globals.

Andriy Ivaneyko
  • 15,838
  • 3
  • 43
  • 65
0

Because calling a variable or function from a user input is dangerous, and particularly if you are only using two different variables, you would be better off using a simple if statement.

This one is a ternary if:

var variable_1 = "foo";
var variable_2 = "bar";

$("input:checked").each(function() {
    var isChecked = $(this).is(':checked');
    var append = (isChecked) ? variable_1 : variable_2;
    $(div).append(append);
}

Alternatively you could use a switch statement for multiple values.

Tim Ogilvy
  • 1,774
  • 1
  • 21
  • 33
  • Right, it could be bad to rely on the input value to show the next menu. Might it be better to have a server-side event push the data back to the client? This would prevent some wise guy changing the values from affecting the next menu. – Matt Pierce Mar 16 '16 at 13:41
0

If the variables are globals then you can use

var y = window["variable_" + x];

to read or

window["variable_" + x] = y;

to write to them dynamically.

Better practice however is to use an object to store them instead of using separate variables...

var data = { variable_1: null,
             variable_2: null };

...

y = data["variable_" + x];

Javascript can also use eval to access dynamically variables, amazingly enough even local variables

function foo(s) {
    var x = 12;
    return eval(s);
}

console.log(foo("x"));

and even more amazingly this allows the dynamic creation of new local variables...

var y = 42;

function foo(s) {
    var x = 1;
    eval(s);
    return y; // may be global y or a local y defined by code in s
}

foo("x")          // returns 42
foo("var y = 99") // returns 99 (but global y is not changed!) 

but these uses of eval should be considered more a bug than a feature and are best avoided (they also makes the code basically impossible to optimize or understand so "just don't do it"™).

6502
  • 104,192
  • 14
  • 145
  • 251