2

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);
});
3
  • What is your goal? You store the values of select boxes and then what? Commented Nov 10, 2013 at 17:46
  • It's not very clear what you want to do, but with a high probability you need a single object instead of many separate variables. Commented Nov 10, 2013 at 17:46
  • @ArtyomNeustroev the goal is to cut down the multiple lines of before and cut it down into an .each() function that will write it and I am unable to add val to the end of the id variable to declare. Commented Nov 10, 2013 at 17:47

2 Answers 2

1

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/

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

2 Comments

in my before example the id name has the letters 'val' after it. how can this be introduced?
appOptions[id + 'val']
1

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.

3 Comments

What's the point of the array? Why not just use the ids as object keys?
I think @beardy wants id and value of select box
Yes, and you can store the id in the keys just as well. If you have an array with separate objects it'll be a pain to find anything from there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.