28

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?

1

3 Answers 3

37

How about something like:

var values = [];
$('#my_dropdown option').each(function() { 
    values.push( $(this).attr('value') );
});
Sign up to request clarification or add additional context in comments.

Comments

9

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

2 Comments

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

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

2 Comments

I like the fall back to text if there is no value :p
@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.

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.