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!

3
  • If the variables are global, use window['variable_' + $(this).val()] Commented Mar 16, 2016 at 5: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()]) Commented Mar 16, 2016 at 6:03
  • You can use eval to get value of any variable dynamically. like $(div).append(eval("variable_" + $(this).val())) Commented Mar 16, 2016 at 6:57

4 Answers 4

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.

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

2 Comments

eval is a very dangerous bit of code tho.
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
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.

1 Comment

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.
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"™).

Comments

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.

3 Comments

putting variables on the window object is not best practice.
@TimOgilvy Well, thanks for your suggestion.
So by concatenating a string you avoid it calling any meaningful method or property. Makes sense to me now.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.