bba
bba

Reputation: 15231

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?

Upvotes: 28

Views: 59225

Answers (3)

jAndy
jAndy

Reputation: 236152

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

Upvotes: 9

user113716
user113716

Reputation: 322582

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

Upvotes: 5

VoteyDisciple
VoteyDisciple

Reputation: 37813

How about something like:

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

Upvotes: 37

Related Questions