views:

3896

answers:

5

How can I get all the options of a select through Jquery by passing on its ID?

Edit: Only looking to get their values, not the text

+5  A: 

I don't know jquery, but 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
KooiInc
+1. Don't resort to jQuery's complex selector magic for things that already have quite efficient implementations built into the plain old DOM.
bobince
+10  A: 

Second time I write an answer like that today...

$("#id option").each(function()
{
    // add $(this).val() to your list
});
ybo
i looove you ybo ;)
Click Upvote
A: 
   $('select#id').find('option').each(function() {
      alert($(this).val());
     });
Raibaz
A: 

This will put the option values of #myselectbox into a nice clean array for you:

// first get the elements into a list
var domelts = $('#myselectbox option');
// next translate that into an array of just the values
var values = $.map(domelts, function(elt, i) { return $(elt).val();});
Thomas Petersen
+1  A: 

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

$("select#example").children().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).

Edit, correction: 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.

cic
You can actually use this.value instead of $(this).val() here. You'd also be better served by finding the children in the initial selector (#example option). Nice tough with the get() at the end though.
Alex Barrett
@Alex Barret: Well, it's possible to solve this problem without using jQuery at all. Calling jQuery with an element as argument will just wrap the element in a jQuery object (i.e. no tree traversing, i.e. not that expensive). So maybe as a micro-optimization, yes.
cic