Javascript Selecbox.options To Array?
Solution 1:
The most concise solution is this:
Array.apply(null, selectbox.options)
Array.apply
calls the Array
constructor with the first argument as the context (i.e. this
) and the second argument which is any array-like object (MDN reference).
We pass null
for the first argument because we're not trying to call a method on a specific object, but rather a global constructor.
So in general,
Array.apply(null, A)
Will create a proper array containing the elements of any "array-like" object A
.
Solution 2:
It is not an array. It is an object. It is "array-like"
from http://api.jquery.com/jQuery.each/ which CAN iterate over either:
Iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties.
Each HTML Option element has a value and a text and some more attributes.
A simple for loop can be used
vals = []
var sel = document.querySelector("select");
for (var i=0, n=sel.options.length;i<n;i++) { // looping over the optionsif (sel.options[i].value) vals.push(sel.options[i].value);
}
the Array.apply posted by typeracer will return an array of HTMLOptionElements which still needs to be looped over or mapped to get at the values and texts
Here are a few versions that will return the same.
This fiddle will run in IE11 too
var vals, sel = document.querySelector("select"), show=function(vals) {$("#result").append("[" + vals.join("][") + "]<hr/>");}
var supportsES6 = function() {try{newFunction("(a = 0) => a");returntrue;}catch (err) {returnfalse; }}();
// jQuery mapping jQuery objects - note the "this" and the .get()
vals = $('select > option').map(function() {returnthis.value;}).get();
show(vals);
// plain JS using loop over select options
vals = [];
for (var i = 0, n = sel.options.length; i < n; i++) { // looping over the optionsif (sel.options[i].value) vals.push(sel.options[i].value); // a bit of testing never hurts
}
show(vals);
// Plain JS using map of HTMLOptionElements - note the el
vals = Array.apply(null, sel.options).map(function(el) { return el.value; });
show(vals);
// ES6 JS using spread and map of HTMLOptionElements - note the fat arrow and elif (supportsES6)
document.write(`<script>
vals = [...sel.options].map(el => el.value);
show(vals);
<\/script>`
);
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script><select><optionvalue="Please select">Text 0</option><optionvalue="one">Text 1</option><optionvalue="two">Text 2</option><optionvalue="three">Text 3</option></select><br/>
The above select has the following option values:<br/><spanid="result"></span>
Solution 3:
To get all the values into an array:
var options = document.getElementById('selectId').options;
var values = [];
var i = 0, len = options.length;
while (i < len)
{
values.push(options[i++].value);
}
alert(values.join(', '));
Fiddle:http://jsfiddle.net/garreh/64pyb/1/
wow a long way to do something short
Well you can use a for loop, not much shorter but more ugly;
for (var options = document.getElementById('selectId').options,
values, i = 0, len = options.length; i < len;i++)
values.push(options[i].value);
alert(values.join(', '));
Then again it's a shame you're not using a library like jQuery. You could do:
$('select > option').map(function() { returnthis.value; }).get();
Solution 4:
selecbox.options
is a (nodeList) collection. You can iterate over it's element like you do with an array an push the members of the collection to a real array.
For the record: in all browsers but IE<9 you can use [].slice.call(selecbox.options);
to quickly convert a collection to an array.
So a crossbrowser way to convert a nodeList collection to array would be:
functioncoll2array(coll){
var ret = [];
try {
ret = [].slice.call(coll)
}
catch(e) {
for (var i =0;i<coll.length;i++){
ret.push(coll[i]);
}
}
return ret;
}
[edit] Nowadays (ES2015 and up) we can use Array.from([arraylike object])
.
or Array.prototype.slice.call([some collection])
Solution 5:
The spread operator makes it really easy ([ ...ElementList ]
).
So for your case you can do the following:
arr = document.getElementById('store-locator-region')
Then convert the html select element to an object array using the spread operator:
newArr = [...arr]
And then iterate over your object array to get your final array:
countryList = newArr.map(a => a.value)
(97) ["XE", "AL", "DZ", "AD", "AR", "AM", etc..]
Post a Comment for "Javascript Selecbox.options To Array?"