How to get all options of a select using jQuery?

Solution 1:

Use:

$("#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

A 12 year old answer. Let's modernize it a bit:

console.log( [...document.querySelector("#demo").options].map( opt => opt.value ) );
<select id="demo">
  <option value="Belgium">Belgium</option>
  <option value="Botswana">Botswana</option>
  <option value="Burkina Faso">Burkina Faso</option>
  <option value="Burundi">Burundi</option>
  <option value="China">China</option>
  <option value="France">France</option>
  <option value="Germany">Germany</option>
  <option value="India">India</option>
  <option value="Japan">Japan</option>
  <option value="Malaysia">Malaysia</option>
  <option value="Mali">Mali</option>
  <option value="Namibia">Namibia</option>
  <option value="Netherlands">Netherlands</option>
  <option value="North Korea">North Korea</option>
  <option value="South Korea">South Korea</option>
  <option value="Spain">Spain</option>
  <option value="Sweden">Sweden</option>
  <option value="Uzbekistan">Uzbekistan</option>
  <option value="Zimbabwe">Zimbabwe</option>
</select>

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/jQuery.map"; 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.