document.getElementsByName returns null in jquery [duplicate] - javascript

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

Related

There is a way to get all the option values in the SELECT TAG without an ID?

do you know if there is a way to take all the values in the OPTION VALUE included in a SELECT?
i Will show you an example, I have this code:
<SELECT onChange="chData(this,this.value)">
<OPTION VALUE=MIPS1 >MIPS
<OPTION VALUE=MSU1 >MSU
<OPTION VALUE=PERCEN1 >% CEC
<OPTION VALUE=NUMGCP1 >nCPU
</SELECT>
I only know the first value which is MIPS1, and I need to take the other values. The is a way to write that if I know the first MIPS1 I will search for the other values Included from the ?
Thanks in advance :)
You can get the <select> element that has an option with a specific value using something like this:
const select = document.querySelector('option[value=MIPS1]').closest('select');
Once you have the <select> element you can retrieve it's options using something like this:
const options = select.querySelectorAll('option');
Or:
const options = select.options;
As #charlietfl mentioned, .closest is not supported by all browsers, instead of that, you could use .parentElement.
jQuery version
var opt = "MIPS1";
const $sel = $("option[value='"+opt+"']").parent()
const options = $("option",$sel).map(function() { return this.value }).get()
console.log(options);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<SELECT onChange="chData(this,this.value)">
<OPTION VALUE=MIPS1>MIPS
<OPTION VALUE=MSU1>MSU
<OPTION VALUE=PERCEN1>% CEC
<OPTION VALUE=NUMGCP1>nCPU
</SELECT>
The example below shows how you can do this. The Jquery is fully commented.
Let me know if it isn't what you were hoping for.
Demo
// Create array
var options = [];
// Load option value you're looking for into a variable
var search_term = "MIPS1";
// Find option with known value, travel up DOM tree to select and then find all options within it
$("option[value='" + search_term + "']").closest("select").find("option").each(function() {
// Add values to array
options.push($(this).val());
});
// Print the array
console.log(options);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<SELECT onChange="chData(this,this.value)">
<OPTION VALUE=MIPS1>MIPS
<OPTION VALUE=MSU1>MSU
<OPTION VALUE=PERCEN1>% CEC
<OPTION VALUE=NUMGCP1>nCPU
</SELECT>
I think it is a bad idea not to give id to your html element in the first place, however if you need to do it that way, then the code below assumes you have only one select tag on your page.
let select = document.querySelector('select');
options = select.childNodes.filter((c) => c.tagName==='OPTION')
.map((o) => o.value);
console.log(options)
This will help you get: selected value, selected text and all the values in the dropdown.
$(document).ready(function(){
$("button").click(function(){
var option = $('option[value="MIPS1"]');
var select = option.parent();
var value = $(select).find(":selected").val();
var optionName = $(select).find(":selected").text();
var result = "value = "+value+"\noption name = "+optionName+"\nall values = ";
$(select).each(function(){
result+=($(this).text()+" ");
});
console.log(result);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
<option value=MIPS1 >MIPS</option>
<option value=MSU1 >MSU</option>
<option value=PERCEN1 >% CEC</option>
<option value=NUMGCP1 >nCPU</option>
</select>
<button>click</button>

How to fill and add text in a text field with drop down selections

I'm not a coder ut I've found this code here
http://jsfiddle.net/kjy112/kchRh/
<textarea id="mytext"></textarea>
<select id="dropdown">
<option value="">None</option>
<option value="text1">text1</option>
<option value="text2">text2</option>
<option value="text3">text3</option>
<option value="text4">text4</option>
</select>
var mytextbox = document.getElementById('mytext');
var mydropdown = document.getElementById('dropdown');
mydropdown.onchange = function(){
mytextbox.value = mytextbox.value + this.value;
}
I'd like to modify it so that I've more than one dropdown and each one add his text in the same field.
Practically I'd have to create a compact code easily for the user so that the user select some phrases using the dropdown and the code will fill the text field.
If I can be more precise please let me know. As said Iìm not a coder so if you can write down the code to use I'll be very happy.
Thanks!
Here's a js bin with multiple dropdowns' onchange event being listed to: https://jsfiddle.net/kchRh/944/
You want to give the dropdowns class names and then loop through each drop down to setup their listeners.
HTML:
<textarea id="mytext"></textarea>
<select class="dropdown">
<option value="">None</option>
<option value="text1">text1</option>
<option value="text2">text2</option>
<option value="text3">text3</option>
<option value="text4">text4</option>
</select>
<select class="dropdown">
<option value="">2None</option>
<option value="2text1">2text1</option>
<option value="2text2">2text2</option>
<option value="2text3">2text3</option>
<option value="2text4">2text4</option>
</select>
JS:
var mytextbox = document.getElementById('mytext');
var mydropdowns = document.getElementsByClassName('dropdown');
for(i=0;i<mydropdowns.length;i++) {
mydropdowns[i].onchange = function(){
mytextbox.value = mytextbox.value + this.value;
}
}
I'd suggest the following approach:
// create a reusable function:
function updateTextArea() {
// get all the elements with the class 'dropdown':
var selectElems = document.querySelectorAll('.dropdown'),
// get the <textarea> element, using its id:
textArea = document.getElementById('mytext'),
// using Array.prototype.filter on the array-like
// NodeList, using Function.prototype.call, in
// order to iterate over the found '.dropdown'
// elements to form an array of only those elements
// with a non-zero-length value:
values = Array.prototype.filter.call(selectElems, function(el) {
if (el.value.trim().length) {
return el.value;
}
// iterating over the filter-created array, to form a map of
// the selected values of the elements:
}).map(function(el) {
return el.value;
// joining those arrays together, with Array.prototype.join,
// to form a comma-separated string of values, and appending
// a period:
}).join(', ') + '.';
// setting the value of the <textarea> to:
// - an empty string (if the values variable is
// just the appended-period), or to the value of
// the values variable:
textArea.value = values === '.' ? '' : values;
}
// as above, retrieving the '.dropdown' elements:
var selects = document.querySelectorAll('.dropdown');
// iterating over the '.dropdown' elements, using
// Array.prototype.forEach:
Array.prototype.forEach.call(selects, function(el, index, arr) {
// within the anonymous function of Array.prototype.foreach:
// the first argument (here: 'el') is the current array-element,
// second argument (here: 'index') is the index of the current
// array-element within the array over which we're iterating,
// third argument (here: 'arr') is the array over which we're
// iterating.
// binding updateTextArea as the change event-handler for
// each of the array-elements over which we iterate:
el.addEventListener('change', updateTextArea);
});
function updateTextArea() {
var selectElems = document.querySelectorAll('.dropdown'),
textArea = document.getElementById('mytext'),
values = Array.prototype.filter.call(selectElems, function(el) {
if (el.value.trim().length) {
return el.value;
}
}).map(function(el) {
return el.value;
}).join(', ') + '.';
textArea.value = values === '.' ? '' : values;
}
var selects = document.querySelectorAll('.dropdown');
Array.prototype.forEach.call(selects, function(el) {
el.addEventListener('change', updateTextArea);
});
<textarea id="mytext"></textarea>
<select class="dropdown">
<option value="">None</option>
<option value="text1">text1</option>
<option value="text2">text2</option>
<option value="text3">text3</option>
<option value="text4">text4</option>
</select>
<select class="dropdown">
<option value="">None</option>
<option value="text5">text5</option>
<option value="text6">text6</option>
<option value="text7">text7</option>
<option value="text8">text8</option>
</select>
JS Fiddle demo.
Note, in the HTML, I've changed from the use of id to identify the <select> elements, to using class; simply because it allows a group of elements to be associated together without having to use a large number of ids and subsequently having to update the JavaScript in turn with the HTML.
Referencs:
Array.prototype.filter().
Array.prototype.forEach().
Array.prototype.join().
Array.prototype.map().
document.querySelectorAll().
eventTarget.addEventListener().
Function.prototype.call().

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 to get all selected values of a multiple select box?

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