ngplayground
ngplayground

Reputation: 21627

Setting variable names in jQuery from a variable

I'm using multiple select boxes on my website and use the id from each of these to select the :selected val and set it as a variable. You will see the 3 randomly chosen below and I'm stuck on adding the word val into the new way of setting multiple variables.

before

var maptypecontrolval       = $('#maptypecontrol>option:selected').val();
var pancontrolval       = $('#pancontrol>option:selected').val();
var clickzoomcontrolval     = $('#clickzoomcontrol>option:selected').val();

after

$(".settings select").each(function(){
    var id = $(this).attr('id');
    console.log(id);
});

Upvotes: 2

Views: 64

Answers (2)

Daniel Gimenez
Daniel Gimenez

Reputation: 20504

Instead of having each option as an individual variable, I would create an object to store all of your variable values.

var appOptions = { };

$(".settings select").each(function() {
  var id = $(this).prop('id');
  appOptions[id] = $(this).val();
});

This approach has the risk of becoming unpredictable if you forget to put an id on a select element in the selector, so you might want to add some validation:

if (!id) throw 'select without id';

As an aside: you got the id value from attr() in your code. You're supposed to use prop(). http://api.jquery.com/prop/

Upvotes: 1

codingrose
codingrose

Reputation: 15699

You can use array and object.

Try this:

var ary = [];
$(".settings select").each(function(){
    var obj = {};
    obj.id = $(this).attr('id');
    obj.val = $(this).find('option:selected').val();
    ary.push(obj);
});
console.log(ary);

ary will contain objects containing ids and values.

Upvotes: 1

Related Questions