2

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.

0

3 Answers 3

4

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]

Example fiddle

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

Comments

3

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];

Example

Comments

0

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]);

});

4 Comments

have you tested this ? I getting undefined as array
I'm sorry, forgot to add .val() to the ch var assignation
edited my code, could you please delete the downvote? It's not the first time someone forgets some piece of code in copy/paste operation. Thanks
unfortunately I'm note the downvoter, but your code works, so +1 ;-)

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.