Get all values in a dropdown select menu?
I know how to get the selected value in an html dropdown menu using jquery.
However, I want 开发者_开发知识库to get an array of all values in the dropdown (i.e. and array containing the value of each <option>
tag in the <select>
), regardless of what is selected or not. What is the proper way to do this?
Pretty simple, using some selectors and an $.each
:
$('select#id_of_select_if_you_want option').each(function(idx, val)
{
$(val).val(); // here's the value
$(val).html(); // here's the display text
});
To get an array of something based on a set of elements, use $.map():
var arrayOfValues = $("#mySelect option").map(function() { return this.value; });
I can't comment on gilly3 (someone with the reputation could help?). His response will give you an object literal, not an array.
If you want an array of values, you can do a map like he suggests, but you need to append the values to a list instead. Here's my version (I'm sure it can be improved):
var all_values = [];
$('#dropdown option').map( function() {
if (this.value.length) {
all_values.push(this.value)
}
});
EDIT:
It looks like, you can use gilly3's answer, but, if you want to actually use the return as an array, you need to append a .get() method.
$('#dropdown option').map( function() {return this.value}).get();
精彩评论