views:

32

answers:

3

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?

A: 

How about something like:

var values = [];
$('#my_dropdown option').each(function() { 
    values.push( $(this).attr('value') );
});
VoteyDisciple
+2  A: 

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()

jAndy
return e.value; (if you want values instead of displayed text) Otherwise, this is a great solution! +1
John Strickler
I always forget about the `map` function +1
Jonathon
+1  A: 

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.)

patrick dw
I like the fall back to text if there is no value :p
John Strickler
@John - Yeah, necessary for IE6, or if the `value` for some reason is an empty string. Otherwise, most browsers will give you the `text` if there isn't a `value` attribute present.
patrick dw