This is my simple markup:
<select id="firstSelect">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
<select id="secondSelect"></select>
In my js there are three different arrays with a progressive name, like these:
var arrayColours1 = new Array('yellow', 'blue');
var arrayColours2 = new Array('red', 'grey');
var arrayColours3 = new Array('white', 'black');
Now I want to popolate the second select with values inside one of the array, according to the selected option of the first select, in this way:
$('#firstSelect').change(function(){
var selectedValue = $(this).children('option:selected').val();
var elem = 'arrayColours'+ selectedValue;
$.each(elem, function (index, value) {
$('<option/>').val(value).html(value).appendTo('#secondSelect');
});
});
But this doesn’t work beacuase of course elem now is a string.
How can solve this issue, concatenating ‘arrayColours’ with a suffix and making it a variable for call the name of an array?
Thank you so much in advance for your attention, any help will be strongly appreciated.
It’s easier than you think.
When you need a concrete set of colours just do this:
Associative arrays are your way to go!