[javascript] 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.

This question is related to javascript jquery jquery-selectors

The answer is


If you're looking for all options with some selected text then the below code will work.

$('#test').find("select option:contains('B')").filter(":selected");

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

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

// First, get the elements into a list
var options = $('#myselectbox option');

// Next, translate that into an array of just the values
var values = $.map(options, e => $(e).val())

    var arr = [], option='';
$('select#idunit').find('option').each(function(index) {
arr.push ([$(this).val(),$(this).text()]);
//option = '<option '+ ((result[0].idunit==arr[index][0])?'selected':'') +'  value="'+arr[index][0]+'">'+arr[index][1]+'</option>';
            });
console.log(arr);
//$('select#idunit').empty();
//$('select#idunit').html(option);

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

The short way

$(() => {
$('#myselect option').each((index, data) => {
    console.log(data.attributes.value.value)
})})

or

export function GetSelectValues(id) {
const mData = document.getElementById(id);
let arry = [];
for (let index = 0; index < mData.children.length; index++) {
    arry.push(mData.children[index].value);
}
return arry;}

I found it short and simple, and can be tested in Dev Tool console itself.

$('#id option').each( (index,element)=>console.log( index : ${index}, value : ${element.value}, text : ${element.text}) )


Here is a simple example in jquery to get all the values, texts, or value of the selected item, or text of the selected item

$('#nCS1 > option').each((index, obj) => {
   console.log($(obj).val());
})

_x000D_
_x000D_
printOptionValues = () => {_x000D_
_x000D_
  $('#nCS1 > option').each((index, obj) => {_x000D_
    console.log($(obj).val());_x000D_
  })_x000D_
_x000D_
}_x000D_
_x000D_
printOptionTexts = () => {_x000D_
  $('#nCS1 > option').each((index, obj) => {_x000D_
    console.log($(obj).text());_x000D_
  })_x000D_
}_x000D_
_x000D_
printSelectedItemText = () => {_x000D_
  console.log($('#nCS1 option:selected').text());_x000D_
}_x000D_
_x000D_
printSelectedItemValue = () => {_x000D_
  console.log($('#nCS1 option:selected').val());_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<select size="1" id="nCS1" name="nCS1" class="form-control" >_x000D_
     <option value="22">Australia</option>_x000D_
          <option value="23">Brunei</option>_x000D_
          <option value="33">Cambodia</option>_x000D_
          <option value="32">Canada</option>_x000D_
          <option value="27">Dubai</option>_x000D_
          <option value="28">Indonesia</option>_x000D_
          <option value="25">Malaysia</option>    _x000D_
</select>_x000D_
<br/>_x000D_
<input type='button' onclick='printOptionValues()' value='print option values' />_x000D_
<br/>_x000D_
<input type='button' onclick='printOptionTexts()' value='print option texts' />_x000D_
<br/>_x000D_
<input type='button' onclick='printSelectedItemText()' value='print selected option text'/>_x000D_
<br/>_x000D_
<input type='button' onclick='printSelectedItemValue()' value='print selected option value' />
_x000D_
_x000D_
_x000D_


$('select#id').find('option').each(function() {
    alert($(this).val());
});

$("input[type=checkbox][checked]").serializeArray();

Or:

$(".some_class[type=checkbox][checked]").serializeArray();

To see the results:

alert($("input[type=checkbox][checked]").serializeArray().toSource());

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


Working example

The most efficient way to do this is to use $.map()

Example:

var values = $.map($('#selectBox option'), function(ele) {
   return ele.value; 
});

For multiselect option:

$('#test').val() returns list of selected values. $('#test option').length returns total number of options (both selected and not selected)


You can take all your "selected values" by the name of the checkboxes and present them in a sting separated by ",".

A nice way to do this is to use jQuery's $.map():

var selected_val = $.map($("input[name='d_name']:checked"), function(a)
    {
        return a.value;
    }).join(',');

alert(selected_val);

This is a simple Script with jQuery:

var items = $("#IDSELECT > option").map(function() {
    var opt = {};
    opt[$(this).val()] = $(this).text();
    return opt;
}).get();
var selectvalues = [];

for(var i = 0; i < items.length; i++) {
    for(key in items[i]) {


        var id = key;
        var text = items[i][key];

        item = {}
        item ["id"] = id;
        item ["text"] = text;

        selectvalues.push(item);

    }
}
console.log(selectvalues);
copy(selectvalues);
<select>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

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.


You can use following code for that:

var assignedRoleId = new Array();
$('#RolesListAssigned option').each(function(){
    assignedRoleId.push(this.value);
});

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to jquery-selectors

Why is my JQuery selector returning a n.fn.init[0], and what is it? How to use placeholder as default value in select2 framework Access the css ":after" selector with jQuery jQuery: using a variable as a selector Check if any ancestor has a class using jQuery jQuery selector first td of each row Select element by exact match of its content jQuery selector to get form by name jQuery : select all element with custom attribute Set select option 'selected', by value