Chris Lex
Chris Lex

Reputation: 25

Dynamically set global JS variables

I am wondering on how to dynamically set JS values. To better understand what I am trying to accomplish, here's a php example:

$first;
$second;
$third;

$my_array = ('first' => 'val_1','second' => 'val_2','third' => 'val_3');
foreach ($my_array as $key => $value){
  $$key = $value;
}

let's say you have a ton of input boxes with a unique ID in html form and you want to use the id as a global variable using jquery or js, that's when I am a bit confused how I can dynamically assign already defined global variables from an Each statement.

The type of html I want to identify through js.

<input id='first' value='val_1'>
<input id='second' value='val_2'>
<input id='third' value='val_3'>

The JS/jquery code

var first;
var second;
var third;

$('input').each(function(){
  var item_id = $(this).attr('id');
  var item_value = $(this).attr('value');

  /* now what... */
});

in the php example the extra dollar sign make the dollar to say I want to populate a variable named like the variable stored in $key. I am wondering if the same can be accomplished with JS or jquery.

The purpose is to manage the amount of values only by adding inputs to the HTML form without the need for altering the JS code considerably.

Upvotes: 1

Views: 184

Answers (2)

Nick
Nick

Reputation: 147196

This isn't good programming style in PHP or JavaScript. Just use an array instead:

var values = [];
$('input').each(function() {
  var item_id = $(this).attr('id');
  var item_value = $(this).attr('value');
  values[item_id] = item_value;
});
console.log('first = ' + values['first'] + ', second = ' + values['second']);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="first">First: </label>
<input id="first" type="text" value="hello" />
<label for="second">Second: </label>
<input id="second" type="text" value="world!" />
<label for="third">Third: </label>
<input id="third" type="text" />

Upvotes: 1

Vineesh
Vineesh

Reputation: 3782

You can use eval function

var first;
var second;
var third;

$('input').each(function(){
  var item_id = $(this).attr('id');
  var item_value = $(this).attr('value');
  eval(item_id+'='+item_value);
});

For example

var v1 = 'first';
var v2 = 'second';
var val1 = 10;
var val2 = 20;
var first;
var second;

eval(v1+'='+val1);
eval(v2+'='+val2);
console.log('first='+first,'second='+second);

Upvotes: 1

Related Questions