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开发者_Python百科. 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.
You need to map val()
over all the <option>
elements in your dropdown list:
iterate_models = $.map($("#listA option"), function(e) {
return $(e).val();
});
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
精彩评论