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
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
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
Second time I write an answer like that today...
$("#id option").each(function()
{
// add $(this).val() to your list
});
$('select#id').find('option').each(function() {
alert($(this).val());
});
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();});
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
.