How to get all selected values of a multiple select box? - javascript

I have a <select> element with the multiple attribute. How can I get this element's selected values using JavaScript?
Here's what I'm trying:
function loopSelected() {
var txtSelectedValuesObj = document.getElementById('txtSelectedValues');
var selectedArray = new Array();
var selObj = document.getElementById('slct');
var i;
var count = 0;
for (i=0; i<selObj.options.length; i++) {
if (selObj.options[i].selected) {
selectedArray[count] = selObj.options[i].value;
count++;
}
}
txtSelectedValuesObj.value = selectedArray;
}

No jQuery:
// Return an array of the selected opion values
// select is an HTML select element
function getSelectValues(select) {
var result = [];
var options = select && select.options;
var opt;
for (var i=0, iLen=options.length; i<iLen; i++) {
opt = options[i];
if (opt.selected) {
result.push(opt.value || opt.text);
}
}
return result;
}
Quick example:
<select multiple>
<option>opt 1 text
<option value="opt 2 value">opt 2 text
</select>
<button onclick="
var el = document.getElementsByTagName('select')[0];
alert(getSelectValues(el));
">Show selected values</button>

With jQuery, the usual way:
var values = $('#select-meal-type').val();
From the docs:
In the case of <select multiple="multiple"> elements, the .val() method returns an array containing each selected option;

Actually, I found the best, most-succinct, fastest, and most-compatible way using pure JavaScript (assuming you don't need to fully support IE lte 8) is the following:
var values = Array.prototype.slice.call(document.querySelectorAll('#select-meal-type option:checked'),0).map(function(v,i,a) {
return v.value;
});
UPDATE (2017-02-14):
An even more succinct way using ES6/ES2015 (for the browsers that support it):
const selected = document.querySelectorAll('#select-meal-type option:checked');
const values = Array.from(selected).map(el => el.value);

You can use selectedOptions property
var options = document.getElementById('select-meal-type').selectedOptions;
var values = Array.from(options).map(({ value }) => value);
console.log(values);
<select id="select-meal-type" multiple="multiple">
<option value="1">Breakfast</option>
<option value="2" selected>Lunch</option>
<option value="3">Dinner</option>
<option value="4" selected>Snacks</option>
<option value="5">Dessert</option>
</select>

ES6
[...select.options].filter(option => option.selected).map(option => option.value)
Where select is a reference to the <select> element.
To break it down:
[...select.options] takes the Array-like list of options and destructures it so that we can use Array.prototype methods on it (Edit: also consider using Array.from())
filter(...) reduces the options to only the ones that are selected
map(...) converts the raw <option> elements into their respective values

If you wanna go the modern way, you can do this:
const selectedOpts = [...field.options].filter(x => x.selected);
The ... operator maps iterable (HTMLOptionsCollection) to the array.
If you're just interested in the values, you can add a map() call:
const selectedValues = [...field.options]
.filter(x => x.selected)
.map(x => x.value);

Check-it Out:
HTML:
<a id="aSelect" href="#">Select</a>
<br />
<asp:ListBox ID="lstSelect" runat="server" SelectionMode="Multiple" Width="100px">
<asp:ListItem Text="Raj" Value="1"></asp:ListItem>
<asp:ListItem Text="Karan" Value="2"></asp:ListItem>
<asp:ListItem Text="Riya" Value="3"></asp:ListItem>
<asp:ListItem Text="Aman" Value="4"></asp:ListItem>
<asp:ListItem Text="Tom" Value="5"></asp:ListItem>
</asp:ListBox>
JQUERY:
$("#aSelect").click(function(){
var selectedValues = [];
$("#lstSelect :selected").each(function(){
selectedValues.push($(this).val());
});
alert(selectedValues);
return false;
});
CLICK HERE TO SEE THE DEMO

First, use Array.from to convert the HTMLCollection object to an array.
let selectElement = document.getElementById('categorySelect')
let selectedValues = Array.from(selectElement.selectedOptions)
.map(option => option.value) // make sure you know what '.map' does
// you could also do: selectElement.options

suppose the multiSelect is the Multiple-Select-Element, just use its selectedOptions Property:
//show all selected options in the console:
for ( var i = 0; i < multiSelect.selectedOptions.length; i++) {
console.log( multiSelect.selectedOptions[i].value);
}

$('#select-meal-type :selected') will contain an array of all of the selected items.
$('#select-meal-type option:selected').each(function() {
alert($(this).val());
});
​

Pretty much the same as already suggested but a bit different. About as much code as jQuery in Vanilla JS:
selected = Array.prototype.filter.apply(
select.options, [
function(o) {
return o.selected;
}
]
);
It seems to be faster than a loop in IE, FF and Safari. I find it interesting that it's slower in Chrome and Opera.
Another approach would be using selectors:
selected = Array.prototype.map.apply(
select.querySelectorAll('option[selected="selected"]'),
[function (o) { return o.value; }]
);

Update October 2019
The following should work "stand-alone" on all modern browsers without any dependencies or transpilation.
<!-- display a pop-up with the selected values from the <select> element -->
<script>
const showSelectedOptions = options => alert(
[...options].filter(o => o.selected).map(o => o.value)
)
</script>
<select multiple onchange="showSelectedOptions(this.options)">
<option value='1'>one</option>
<option value='2'>two</option>
<option value='3'>three</option>
<option value='4'>four</option>
</select>

If you need to respond to changes, you can try this:
document.getElementById('select-meal-type').addEventListener('change', function(e) {
let values = [].slice.call(e.target.selectedOptions).map(a => a.value));
})
The [].slice.call(e.target.selectedOptions) is needed because e.target.selectedOptions returns a HTMLCollection, not an Array. That call converts it to Array so that we can then apply the map function, which extract the values.

Check this:
HTML:
<select id="test" multiple>
<option value="red" selected>Red</option>
<option value="rock" selected>Rock</option>
<option value="sun">Sun</option>
</select>
Javascript one line code
Array.from(document.getElementById("test").options).filter(option => option.selected).map(option => option.value);

if you want as you expressed with breaks after each value;
$('#select-meal-type').change(function(){
var meals = $(this).val();
var selectedmeals = meals.join(", "); // there is a break after comma
alert (selectedmeals); // just for testing what will be printed
})

Try this:
$('#select-meal-type').change(function(){
var arr = $(this).val()
});
Demo
$('#select-meal-type').change(function(){
var arr = $(this).val();
console.log(arr)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select-meal-type" multiple="multiple">
<option value="1">Breakfast</option>
<option value="2">Lunch</option>
<option value="3">Dinner</option>
<option value="4">Snacks</option>
<option value="5">Dessert</option>
</select>
fiddle

Here is an ES6 implementation:
value = Array(...el.options).reduce((acc, option) => {
if (option.selected === true) {
acc.push(option.value);
}
return acc;
}, []);

Building on Rick Viscomi's answer, try using the HTML Select Element's selectedOptions property:
let txtSelectedValuesObj = document.getElementById('txtSelectedValues');
[...txtSelectedValuesObj.selectedOptions].map(option => option.value);
In detail,
selectedOptions returns a list of selected items.
Specifically, it returns a read-only HTMLCollection containing HTMLOptionElements.
... is spread syntax. It expands the HTMLCollection's elements.
[...] creates a mutable Array object from these elements, giving you an array of HTMLOptionElements.
map() replaces each HTMLObjectElement in the array (here called option) with its value (option.value).
Dense, but it seems to work.
Watch out, selectedOptions isn't supported by IE!

You can get as an array the values from the <select> at the submit of the form as this example :
const form = document.getElementById('form-upload');
form.addEventListener('change', (e) => {
const formData = new FormData(form);
const selectValue = formData.getAll('pets');
console.log(selectValue);
})
<form id="form-upload">
<select name="pets" multiple id="pet-select">
<option value="">--Please choose an option--</option>
<option value="dog">Dog</option>
<option value="cat">Cat</option>
<option value="hamster">Hamster</option>
<option value="parrot">Parrot</option>
<option value="spider">Spider</option>
<option value="goldfish">Goldfish</option>
</select>
</form>

Something like the following would be my choice:
let selectElement = document.getElementById('categorySelect');
let selectedOptions = selectElement.selectedOptions || [].filter.call(selectedElement.options, option => option.selected);
let selectedValues = [].map.call(selectedOptions, option => option.value);
It's short, it's fast on modern browsers, and we don't care whether it's fast or not on 1% market share browsers.
Note, selectedOptions has wonky behavior on some browsers from around 5 years ago, so a user agent sniff isn't totally out of line here.

You Can try this script
<!DOCTYPE html>
<html>
<script>
function getMultipleSelectedValue()
{
var x=document.getElementById("alpha");
for (var i = 0; i < x.options.length; i++) {
if(x.options[i].selected ==true){
alert(x.options[i].value);
}
}
}
</script>
</head>
<body>
<select multiple="multiple" id="alpha">
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
<option value="d">D</option>
</select>
<input type="button" value="Submit" onclick="getMultipleSelectedValue()"/>
</body>
</html>

You can use [].reduce for a more compact implementation of RobG's approach:
var getSelectedValues = function(selectElement) {
return [].reduce.call(selectElement.options, function(result, option) {
if (option.selected) result.push(option.value);
return result;
}, []);
};

My template helper looks like this:
'submit #update': function(event) {
event.preventDefault();
var obj_opts = event.target.tags.selectedOptions; //returns HTMLCollection
var array_opts = Object.values(obj_opts); //convert to array
var stray = array_opts.map((o)=> o.text ); //to filter your bits: text, value or selected
//do stuff
}

Same as the earlier answer but using underscore.js.
function getSelectValues(select) {
return _.map(_.filter(select.options, function(opt) {
return opt.selected; }), function(opt) {
return opt.value || opt.text; });
}

Works everywhere without jquery:
var getSelectValues = function (select) {
var ret = [];
// fast but not universally supported
if (select.selectedOptions != undefined) {
for (var i=0; i < select.selectedOptions.length; i++) {
ret.push(select.selectedOptions[i].value);
}
// compatible, but can be painfully slow
} else {
for (var i=0; i < select.options.length; i++) {
if (select.options[i].selected) {
ret.push(select.options[i].value);
}
}
}
return ret;
};

Here ya go.
const arr = Array.from(el.features.selectedOptions) //get array from selectedOptions property
const list = []
arr.forEach(item => list.push(item.value)) //push each item to empty array
console.log(list)

$('#application_student_groups option:selected').toArray().map(item => item.value)

You can create your own function like this and use it everywhere
Pure JS
/**
* Get values from multiple select input field
* #param {string} selectId - the HTML select id of the select field
**/
function getMultiSelectValues(selectId) {
// get the options of select field which will be HTMLCollection
// remember HtmlCollection and not an array. You can always enhance the code by
// verifying if the provided select is valid or not
var options = document.getElementById(selectId).options;
var values = [];
// since options are HtmlCollection, we convert it into array to use map function on it
Array.from(options).map(function(option) {
option.selected ? values.push(option.value) : null
})
return values;
}
you can get the same result using jQuery in a single line
$('#select_field_id').val()
and this will return the array of values of well.

Related

document.getElementsByName returns null in jquery [duplicate]

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.
Use:
$("#id option").each(function()
{
// Add $(this).val() to your list
});
.each() | jQuery API Documentation
Without jQuery
I do know that the HTMLSelectElement element contains an options property, which is a HTMLOptionsCollection.
const myOpts = document.getElementById('yourselect').options;
console.log(myOpts[0].value) //=> Value of the first option
A 12 year old answer. Let's modernize it a bit (using .querySelectorAll, spreading the resulting HTMLOptionsCollection to Array and map the values).
// helper to retrieve an array of elements using a css selector
const nodes = selector => [...document.querySelectorAll(selector)];
const results = {
pojs: nodes(`#demo option`).map(o => o.value),
jq: $(`#demo option`).toArray().map( o => o.value ),
}
console.log( `pojs: [${results.pojs.slice(0, 5)}]` );
console.log( `jq: [${results.jq.slice(0, 5)}]` );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<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>
$.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.
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.
$('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 options = $('#myselectbox option');
// Next, translate that into an array of just the values
var values = $.map(options, e => $(e).val())
$("#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);
});
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);
Working example
The most efficient way to do this is to use $.map()
Example:
var values = $.map($('#selectBox option'), function(ele) {
return ele.value;
});
You can use following code for that:
var assignedRoleId = new Array();
$('#RolesListAssigned option').each(function(){
assignedRoleId.push(this.value);
});
For multiselect option:
$('#test').val() returns list of selected values.
$('#test option').length returns total number of options (both selected and not selected)
Another way would be to use toArray() in order to use fat arrow function with map e.g:
const options = $('#myselect option').toArray().map(it => $(it).val())
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());
})
printOptionValues = () => {
$('#nCS1 > option').each((index, obj) => {
console.log($(obj).val());
})
}
printOptionTexts = () => {
$('#nCS1 > option').each((index, obj) => {
console.log($(obj).text());
})
}
printSelectedItemText = () => {
console.log($('#nCS1 option:selected').text());
}
printSelectedItemValue = () => {
console.log($('#nCS1 option:selected').val());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select size="1" id="nCS1" name="nCS1" class="form-control" >
<option value="22">Australia</option>
<option value="23">Brunei</option>
<option value="33">Cambodia</option>
<option value="32">Canada</option>
<option value="27">Dubai</option>
<option value="28">Indonesia</option>
<option value="25">Malaysia</option>
</select>
<br/>
<input type='button' onclick='printOptionValues()' value='print option values' />
<br/>
<input type='button' onclick='printOptionTexts()' value='print option texts' />
<br/>
<input type='button' onclick='printSelectedItemText()' value='print selected option text'/>
<br/>
<input type='button' onclick='printSelectedItemValue()' value='print selected option value' />
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);
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>
This is a very simple way to generate a list of comma separated values.
var values = "";
$('#sel-box option').each(function () {
values = values + $(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());
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");
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}) )
$("select#MY_SELECT_ID").find('option').each(function() {
console.log($(this).val());
console.log($(this).text());
});

How to obtain multiple select options when serializing Form data in javascript (vanilla or jQuery)?

I wrote the following function that turns a div/Form into serialized object. I use this returned to pass into my database javascript calling methods.
Tater.prototype._formToObject = function(formData) {
var p = {};
jQuery.each(jQuery(formData).serializeArray(),function(i, e){
p[e.name] = e.value;
});
return p;
};
The only issue is if I change my form to have a multiple select option, it only grabs the first value of the multiple selected. How would I extend this to allow for such behavior?
Try something along these lines to get the array of values.
If you give us a working snippet of what you are doing it will be easier to adapt to what you want.
Most likely you need to add a check for the multiple attribute on e (see comments below)
else do the current logic that seems to be working
in the below logic replace this with e for your scenario
`
Tater.prototype._formToObject = function(formData) {
const p = {};
jQuery.each(jQuery(formData).serializeArray(),function(i, e){
//check for multiple attr
e.getAttribute('multiple') == null ?
(p[e.name] = e.value) :
(p[e.name] = $(e).val());
});
return p;
};
`
document.getElementById('multi').addEventListener('change', function () {
//jquery
this.getAttribute('multiple') != null && console.log($(this).val());
//vanilla
if(this.getAttribute('multiple') != null) {
const arr = [], nodes = this.querySelectorAll(':checked');
for(let i = 0; i < nodes.length; i++) {
arr.push(nodes[i].value);
}
console.log(arr);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select multiple id="multi">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<!-- from https://www.w3schools.com/tags/att_select_multiple.asp -->

How to get all selected values from <select multiple=multiple>? [duplicate]

I have a <select> element with the multiple attribute. How can I get this element's selected values using JavaScript?
Here's what I'm trying:
function loopSelected() {
var txtSelectedValuesObj = document.getElementById('txtSelectedValues');
var selectedArray = new Array();
var selObj = document.getElementById('slct');
var i;
var count = 0;
for (i=0; i<selObj.options.length; i++) {
if (selObj.options[i].selected) {
selectedArray[count] = selObj.options[i].value;
count++;
}
}
txtSelectedValuesObj.value = selectedArray;
}
No jQuery:
// Return an array of the selected opion values
// select is an HTML select element
function getSelectValues(select) {
var result = [];
var options = select && select.options;
var opt;
for (var i=0, iLen=options.length; i<iLen; i++) {
opt = options[i];
if (opt.selected) {
result.push(opt.value || opt.text);
}
}
return result;
}
Quick example:
<select multiple>
<option>opt 1 text
<option value="opt 2 value">opt 2 text
</select>
<button onclick="
var el = document.getElementsByTagName('select')[0];
alert(getSelectValues(el));
">Show selected values</button>
With jQuery, the usual way:
var values = $('#select-meal-type').val();
From the docs:
In the case of <select multiple="multiple"> elements, the .val() method returns an array containing each selected option;
Actually, I found the best, most-succinct, fastest, and most-compatible way using pure JavaScript (assuming you don't need to fully support IE lte 8) is the following:
var values = Array.prototype.slice.call(document.querySelectorAll('#select-meal-type option:checked'),0).map(function(v,i,a) {
return v.value;
});
UPDATE (2017-02-14):
An even more succinct way using ES6/ES2015 (for the browsers that support it):
const selected = document.querySelectorAll('#select-meal-type option:checked');
const values = Array.from(selected).map(el => el.value);
You can use selectedOptions property
var options = document.getElementById('select-meal-type').selectedOptions;
var values = Array.from(options).map(({ value }) => value);
console.log(values);
<select id="select-meal-type" multiple="multiple">
<option value="1">Breakfast</option>
<option value="2" selected>Lunch</option>
<option value="3">Dinner</option>
<option value="4" selected>Snacks</option>
<option value="5">Dessert</option>
</select>
ES6
[...select.options].filter(option => option.selected).map(option => option.value)
Where select is a reference to the <select> element.
To break it down:
[...select.options] takes the Array-like list of options and destructures it so that we can use Array.prototype methods on it (Edit: also consider using Array.from())
filter(...) reduces the options to only the ones that are selected
map(...) converts the raw <option> elements into their respective values
If you wanna go the modern way, you can do this:
const selectedOpts = [...field.options].filter(x => x.selected);
The ... operator maps iterable (HTMLOptionsCollection) to the array.
If you're just interested in the values, you can add a map() call:
const selectedValues = [...field.options]
.filter(x => x.selected)
.map(x => x.value);
Check-it Out:
HTML:
<a id="aSelect" href="#">Select</a>
<br />
<asp:ListBox ID="lstSelect" runat="server" SelectionMode="Multiple" Width="100px">
<asp:ListItem Text="Raj" Value="1"></asp:ListItem>
<asp:ListItem Text="Karan" Value="2"></asp:ListItem>
<asp:ListItem Text="Riya" Value="3"></asp:ListItem>
<asp:ListItem Text="Aman" Value="4"></asp:ListItem>
<asp:ListItem Text="Tom" Value="5"></asp:ListItem>
</asp:ListBox>
JQUERY:
$("#aSelect").click(function(){
var selectedValues = [];
$("#lstSelect :selected").each(function(){
selectedValues.push($(this).val());
});
alert(selectedValues);
return false;
});
CLICK HERE TO SEE THE DEMO
First, use Array.from to convert the HTMLCollection object to an array.
let selectElement = document.getElementById('categorySelect')
let selectedValues = Array.from(selectElement.selectedOptions)
.map(option => option.value) // make sure you know what '.map' does
// you could also do: selectElement.options
suppose the multiSelect is the Multiple-Select-Element, just use its selectedOptions Property:
//show all selected options in the console:
for ( var i = 0; i < multiSelect.selectedOptions.length; i++) {
console.log( multiSelect.selectedOptions[i].value);
}
$('#select-meal-type :selected') will contain an array of all of the selected items.
$('#select-meal-type option:selected').each(function() {
alert($(this).val());
});
​
Pretty much the same as already suggested but a bit different. About as much code as jQuery in Vanilla JS:
selected = Array.prototype.filter.apply(
select.options, [
function(o) {
return o.selected;
}
]
);
It seems to be faster than a loop in IE, FF and Safari. I find it interesting that it's slower in Chrome and Opera.
Another approach would be using selectors:
selected = Array.prototype.map.apply(
select.querySelectorAll('option[selected="selected"]'),
[function (o) { return o.value; }]
);
Update October 2019
The following should work "stand-alone" on all modern browsers without any dependencies or transpilation.
<!-- display a pop-up with the selected values from the <select> element -->
<script>
const showSelectedOptions = options => alert(
[...options].filter(o => o.selected).map(o => o.value)
)
</script>
<select multiple onchange="showSelectedOptions(this.options)">
<option value='1'>one</option>
<option value='2'>two</option>
<option value='3'>three</option>
<option value='4'>four</option>
</select>
If you need to respond to changes, you can try this:
document.getElementById('select-meal-type').addEventListener('change', function(e) {
let values = [].slice.call(e.target.selectedOptions).map(a => a.value));
})
The [].slice.call(e.target.selectedOptions) is needed because e.target.selectedOptions returns a HTMLCollection, not an Array. That call converts it to Array so that we can then apply the map function, which extract the values.
Check this:
HTML:
<select id="test" multiple>
<option value="red" selected>Red</option>
<option value="rock" selected>Rock</option>
<option value="sun">Sun</option>
</select>
Javascript one line code
Array.from(document.getElementById("test").options).filter(option => option.selected).map(option => option.value);
if you want as you expressed with breaks after each value;
$('#select-meal-type').change(function(){
var meals = $(this).val();
var selectedmeals = meals.join(", "); // there is a break after comma
alert (selectedmeals); // just for testing what will be printed
})
Try this:
$('#select-meal-type').change(function(){
var arr = $(this).val()
});
Demo
$('#select-meal-type').change(function(){
var arr = $(this).val();
console.log(arr)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select-meal-type" multiple="multiple">
<option value="1">Breakfast</option>
<option value="2">Lunch</option>
<option value="3">Dinner</option>
<option value="4">Snacks</option>
<option value="5">Dessert</option>
</select>
fiddle
Here is an ES6 implementation:
value = Array(...el.options).reduce((acc, option) => {
if (option.selected === true) {
acc.push(option.value);
}
return acc;
}, []);
Building on Rick Viscomi's answer, try using the HTML Select Element's selectedOptions property:
let txtSelectedValuesObj = document.getElementById('txtSelectedValues');
[...txtSelectedValuesObj.selectedOptions].map(option => option.value);
In detail,
selectedOptions returns a list of selected items.
Specifically, it returns a read-only HTMLCollection containing HTMLOptionElements.
... is spread syntax. It expands the HTMLCollection's elements.
[...] creates a mutable Array object from these elements, giving you an array of HTMLOptionElements.
map() replaces each HTMLObjectElement in the array (here called option) with its value (option.value).
Dense, but it seems to work.
Watch out, selectedOptions isn't supported by IE!
You can get as an array the values from the <select> at the submit of the form as this example :
const form = document.getElementById('form-upload');
form.addEventListener('change', (e) => {
const formData = new FormData(form);
const selectValue = formData.getAll('pets');
console.log(selectValue);
})
<form id="form-upload">
<select name="pets" multiple id="pet-select">
<option value="">--Please choose an option--</option>
<option value="dog">Dog</option>
<option value="cat">Cat</option>
<option value="hamster">Hamster</option>
<option value="parrot">Parrot</option>
<option value="spider">Spider</option>
<option value="goldfish">Goldfish</option>
</select>
</form>
Something like the following would be my choice:
let selectElement = document.getElementById('categorySelect');
let selectedOptions = selectElement.selectedOptions || [].filter.call(selectedElement.options, option => option.selected);
let selectedValues = [].map.call(selectedOptions, option => option.value);
It's short, it's fast on modern browsers, and we don't care whether it's fast or not on 1% market share browsers.
Note, selectedOptions has wonky behavior on some browsers from around 5 years ago, so a user agent sniff isn't totally out of line here.
You Can try this script
<!DOCTYPE html>
<html>
<script>
function getMultipleSelectedValue()
{
var x=document.getElementById("alpha");
for (var i = 0; i < x.options.length; i++) {
if(x.options[i].selected ==true){
alert(x.options[i].value);
}
}
}
</script>
</head>
<body>
<select multiple="multiple" id="alpha">
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
<option value="d">D</option>
</select>
<input type="button" value="Submit" onclick="getMultipleSelectedValue()"/>
</body>
</html>
You can use [].reduce for a more compact implementation of RobG's approach:
var getSelectedValues = function(selectElement) {
return [].reduce.call(selectElement.options, function(result, option) {
if (option.selected) result.push(option.value);
return result;
}, []);
};
My template helper looks like this:
'submit #update': function(event) {
event.preventDefault();
var obj_opts = event.target.tags.selectedOptions; //returns HTMLCollection
var array_opts = Object.values(obj_opts); //convert to array
var stray = array_opts.map((o)=> o.text ); //to filter your bits: text, value or selected
//do stuff
}
Same as the earlier answer but using underscore.js.
function getSelectValues(select) {
return _.map(_.filter(select.options, function(opt) {
return opt.selected; }), function(opt) {
return opt.value || opt.text; });
}
Works everywhere without jquery:
var getSelectValues = function (select) {
var ret = [];
// fast but not universally supported
if (select.selectedOptions != undefined) {
for (var i=0; i < select.selectedOptions.length; i++) {
ret.push(select.selectedOptions[i].value);
}
// compatible, but can be painfully slow
} else {
for (var i=0; i < select.options.length; i++) {
if (select.options[i].selected) {
ret.push(select.options[i].value);
}
}
}
return ret;
};
Here ya go.
const arr = Array.from(el.features.selectedOptions) //get array from selectedOptions property
const list = []
arr.forEach(item => list.push(item.value)) //push each item to empty array
console.log(list)
$('#application_student_groups option:selected').toArray().map(item => item.value)
You can create your own function like this and use it everywhere
Pure JS
/**
* Get values from multiple select input field
* #param {string} selectId - the HTML select id of the select field
**/
function getMultiSelectValues(selectId) {
// get the options of select field which will be HTMLCollection
// remember HtmlCollection and not an array. You can always enhance the code by
// verifying if the provided select is valid or not
var options = document.getElementById(selectId).options;
var values = [];
// since options are HtmlCollection, we convert it into array to use map function on it
Array.from(options).map(function(option) {
option.selected ? values.push(option.value) : null
})
return values;
}
you can get the same result using jQuery in a single line
$('#select_field_id').val()
and this will return the array of values of well.

How can I replace all option labels of a select with their values?

If I have select element with values which are different from their labels, how can I replace all of the labels with the corresponding values?
Secondly, how can I sort the list alphabetically with the values, all without using any frameworks?
Input:
<select name="options" >
<option value="apple">Fruit</option>
<option value="rye">Bread</option>
<option value="beer">Beverage</option>
</select>
Output:
<select name="options" >
<option value="apple">apple</option>
<option value="beer">beer</option>
<option value="rye">rye</option>
</select>
Sure, using getElementsByTagName() and innerHTML:
var allOptions = document.getElementsByTagName("option");
for (var i=0; i<allOptions.length; i++) {
allOptions[i].innerHTML = allOptions[i].value;
}
Here it is in action.
To sort the options alphabetically, see: Javascript to sort contents of select element
If you would like them to be identical, you can simply omit the value attribute - the string inside the option tag will then be sent to the server as the value. Take a look here: http://www.w3schools.com/tags/att_option_value.asp.
You can do this:
<select name="options" >
<option value="apple">Fruit</option>
<option value="rye">Bread</option>
<option value="beer">Beverage</option>
</select>
<script>
var options = document.getElementsByName("options")[0].querySelectorAll("option");
Array.prototype.slice.call(options).map(function (option) {
option.innerHTML = option.value;
});
</script>
You can encapsulate this in a function to order your select, and order when you remove or add any element to your select.
The function would be something like this:
function sortSelect(selElem) {
var tmpAry = new Array();
for (var i=0;i<selElem.options.length;i++) {
tmpAry[i] = new Array();
tmpAry[i][0] = selElem.options[i].text;
tmpAry[i][1] = selElem.options[i].value;
}
tmpAry.sort();
while (selElem.options.length > 0) {
selElem.options[0] = null;
}
for (var i=0;i<tmpAry.length;i++) {
var op = new Option(tmpAry[i][0], tmpAry[i][1]);
selElem.options[i] = op;
}
return;
}
And you should call it like :
sortSelect(document.getElementsByName("options"));

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.
Use:
$("#id option").each(function()
{
// Add $(this).val() to your list
});
.each() | jQuery API Documentation
Without jQuery
I do know that the HTMLSelectElement element contains an options property, which is a HTMLOptionsCollection.
const myOpts = document.getElementById('yourselect').options;
console.log(myOpts[0].value) //=> Value of the first option
A 12 year old answer. Let's modernize it a bit (using .querySelectorAll, spreading the resulting HTMLOptionsCollection to Array and map the values).
// helper to retrieve an array of elements using a css selector
const nodes = selector => [...document.querySelectorAll(selector)];
const results = {
pojs: nodes(`#demo option`).map(o => o.value),
jq: $(`#demo option`).toArray().map( o => o.value ),
}
console.log( `pojs: [${results.pojs.slice(0, 5)}]` );
console.log( `jq: [${results.jq.slice(0, 5)}]` );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<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>
$.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.
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.
$('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 options = $('#myselectbox option');
// Next, translate that into an array of just the values
var values = $.map(options, e => $(e).val())
$("#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);
});
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);
Working example
The most efficient way to do this is to use $.map()
Example:
var values = $.map($('#selectBox option'), function(ele) {
return ele.value;
});
You can use following code for that:
var assignedRoleId = new Array();
$('#RolesListAssigned option').each(function(){
assignedRoleId.push(this.value);
});
For multiselect option:
$('#test').val() returns list of selected values.
$('#test option').length returns total number of options (both selected and not selected)
Another way would be to use toArray() in order to use fat arrow function with map e.g:
const options = $('#myselect option').toArray().map(it => $(it).val())
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());
})
printOptionValues = () => {
$('#nCS1 > option').each((index, obj) => {
console.log($(obj).val());
})
}
printOptionTexts = () => {
$('#nCS1 > option').each((index, obj) => {
console.log($(obj).text());
})
}
printSelectedItemText = () => {
console.log($('#nCS1 option:selected').text());
}
printSelectedItemValue = () => {
console.log($('#nCS1 option:selected').val());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select size="1" id="nCS1" name="nCS1" class="form-control" >
<option value="22">Australia</option>
<option value="23">Brunei</option>
<option value="33">Cambodia</option>
<option value="32">Canada</option>
<option value="27">Dubai</option>
<option value="28">Indonesia</option>
<option value="25">Malaysia</option>
</select>
<br/>
<input type='button' onclick='printOptionValues()' value='print option values' />
<br/>
<input type='button' onclick='printOptionTexts()' value='print option texts' />
<br/>
<input type='button' onclick='printSelectedItemText()' value='print selected option text'/>
<br/>
<input type='button' onclick='printSelectedItemValue()' value='print selected option value' />
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);
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>
This is a very simple way to generate a list of comma separated values.
var values = "";
$('#sel-box option').each(function () {
values = values + $(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());
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");
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}) )
$("select#MY_SELECT_ID").find('option').each(function() {
console.log($(this).val());
console.log($(this).text());
});

Categories