1

I have an HTML select list (let's call it List A) that is dynamically populated with a list of values. I need to change another select list (List B) depending on the value of List A. That part, I can do. Ordinarily, the user selects one element of List A, and gets a List B contingent on List A.

However, the first element of List A is "All Values." Therefore, in this instance, I want a List B that consists of the aggregate of all of the values possible for List B. Because the available values of List A are dynamically generated, I can't simply pull all List B values. I need to pull all List B values contingent on all List A values shown.

To do this, I want to iterate through all of the values in List A, and append to List B for each item in List A. This is where I'm stuck. How can I populate an array to consist of all of the values in a select list? Again, because List A is populated dynamically, the only way to get a list of these values is to pull them from the select list element.

I tried this:

iterate_models = $.map($('#listA'), function(e) { return $(e).val(); });

This did not give me an array of the values of each element in #listA. I can't figure out why not.

2 Answers 2

3

You need to map val() over all the <option> elements in your dropdown list:

iterate_models = $.map($("#listA option"), function(e) {
    return $(e).val();
});
Sign up to request clarification or add additional context in comments.

1 Comment

Furthermore, you'll probably want to exclude the "All Values" option (e.g. set that option to value="0" and inside your .map() anonymous function put if ($(e).val() != 0) return $(e).val();
1

Your biggest problem here is that your selector will select the actual select element and get it's value. You want all the values of the option elements inside that select. Your selector should therefore be, #listA > option. You need to chain a .get() call on the $.map() call because the return value of $.map() is a jQuery-wrapped array, and you want a basic array, without the jQuery bells and whistles. Also, you can clean up your code by using the .map() variant because you are using map on a jQuery object.

Putting that all together:

var optVals = $("#listA > option").map(function() {
                return this.value;
}).get();
$.each(optVals, function(i, val) {
    alert(val);
});

jsFiddle

Comments

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.