jquery getting all dropdown values
I have dropdown <select>
with id my_dropdown
. I allow multi-select. I know how to pull the selected value(s) using jquery:
var values = $('#my_dropdown').val();
This will return an array of values if I select multiple. I also need to get all the values in the dropdown regardless of what is selected. How can I use jquery similarly to get all the values in the dropdown given that id?
感觉如何:
var values = [];
$('#my_dropdown option').each(function() {
values.push( $(this).attr('value') );
});
Looks like:
var values = $('#my_dropdown').children('option').map(function(i, e){
return e.value || e.innerText;
}).get();
See this in action: http://www.jsfiddle.net/YjC6y/16/
Reference: .map()
Example: http://jsfiddle.net/FadHu/
var opts = $('#my_dropdown')[0].options;
var array = $.map(opts, function( elem ) {
return (elem.value || elem.text);
});
The <select>
element has a list of the options in its options
property. Then use $.map()
, which returns an array, to get either the option's value
or text
property.
(Note the $.map()
behaves a little differently from $(element).map()
. Can be a little tricky.)
上一篇: 使用JavaScript在下拉列表中获取选定的值?
下一篇: jquery获取所有下拉值