Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically Select Variable [duplicate]

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!

like image 320
Matt Pierce Avatar asked Nov 09 '22 18:11

Matt Pierce


1 Answers

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.

like image 200
Ranish Karim Avatar answered Nov 15 '22 10:11

Ranish Karim