How to get all options of a select using jQuery?

How to get all options of a select using jQuery?

How can I get all the options of a select through jQuery by passing on its ID?
I am only looking to get their values, not the text.


Solution 1:


$("#id option").each(function()
    // Add $(this).val() to your list

.each() | jQuery API Documentation

Solution 2:

I don’t know jQuery, but I do know that if you get the select element, it contains an ‘options’ object.

var myOpts = document.getElementById('yourselect').options;
alert(myOpts[0].value) //=> Value of the first option

Solution 3:

$.map is probably the most efficient way to do this.

var options = $('#selectBox option');

var values = $.map(options ,function(option) {
    return option.value;

You can add change options to $('#selectBox option:selected') if you only want the ones that are selected.

The first line selects all of the checkboxes and puts their jQuery element into a variable. We then use the .map function of jQuery to apply a function to each of the elements of that variable; all we are doing is returning the value of each element as that is all we care about. Because we are returning them inside of the map function it actually builds an array of the values just as requested.

Solution 4:

Some answers uses each, but map is a better alternative here IMHO:

$("select#example option").map(function() {return $(this).val();}).get();

There are (at least) two map functions in jQuery. Thomas Petersen’s answer uses “Utilities/”; this answer uses “Traversing/map” (and therefore a little cleaner code).

It depends on what you are going to do with the values. If you, let’s say, want to return the values from a function, map is probably the better alternative. But if you are going to use the values directly you probably want each.

Solution 5:

$('select#id').find('option').each(function() {

Solution 6:

$("#id option").each(function()
    $(this).prop('selected', true);

Although, the CORRECT way is to set the DOM property of the element, like so:

$("#id option").each(function(){
    $(this).attr('selected', true);