Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create dynamic variables using jquery?

I want some jquery variables to be created dynamically. In my code I am having a loop, and with the loop values I want to create some variables. Here is my sample code.

array=["student","parent","employee"]

$.each(user_types, function( index, value ){
  var value+"_type" // this is the type of variable i want to build.
})

I have found about eval function. That code goes like this.

var type = "type"
eval("var pre_"+type+"= 'The value of dynamic variable, val';");

alert(pre_type) // this gives 'The value of dynamic variable, val' in alert box.

Is there any alternate ways as I have read the eval function is not prefered while coding .js files.

like image 772
Deepak A Avatar asked Feb 08 '26 03:02

Deepak A


1 Answers

Any time you find yourself using a variable in the name of a variable, you probably want to use an object literal. Create the object with curly braces {}, and then set the object property key using square bracket notation:

var user_types = ["student","parent","employee"];
var types = {};

$.each(user_types, function( index, value ){
  types[value] = 'The value of dynamic variable, val';
});

JSFiddle

Note: You haven't tagged it, but I assume because you've used each() that you are using jQuery, please correct me if I'm wrong.

like image 80
George Avatar answered Feb 12 '26 05:02

George



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!