QUESTION
How can I populate myArray
with one of the arrays listed and change it using the selected option of a dropdown list?
Using javascript or jQuery
<select id="ddl">
<option>arr1</option>
<option>arr2</option>
<option>arr3</option>
</select>
var arr1 = ['A', 'B', 'C'],
arr2 = ['1', '2', '3'],
arr3 = ['X', 'Y', 'Z'],
array = document.getElementById('ddl').value;
//...
myArray: array
PROBLEM
Currently ddl is just a string value and I need the selected value to be one of the javascript variables.
You can use an object to store your arrays in, then access that object using the string value of the dropdown. Something like this:
var options = {
arr1: ['A', 'B', 'C'],
arr2: ['1', '2', '3'],
arr3: ['X', 'Y', 'Z']
}
var array = options[$('#ddl').val()]; // options[document.getElementById('ddl').value]
You could make a multi dimensional array:
var arr = [];
arr['arr1'] = ['A', 'B', 'C'],
arr['arr2'] = ['1', '2', '3'],
arr['arr3'] = ['X', 'Y', 'Z'];
var selectedArray = arr[document.getElementById('ddl').value];
What about that using the concept of @Rory McCrossan and adding the right values to the option?
<select id="ddl">
<option value="0">arr1</option>
<option value="1">arr2</option>
<option value="2">arr3</option>
</select>
var options =[
['A', 'B', 'C'],
['1', '2', '3'],
['X', 'Y', 'Z']
];
$('#ddl').change(function () {
var ch = $('#ddl').val();
var array = options[ch];
//test
alert(options[ch]);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.