From what I understand a option
elements that popuate select
elements in HTML are an array.
So basically what i want to do is return an array string that is separated by commas.
Tried to do selecbox.options.join(',');
, but got an error that its not supported; anyone have an idea why?
You can join an array of strings, but an option is not a string, it's an object with all kinds of properties like value and text. Which should it use to join?
You just have to write a loop to append all values you want.
Or use a library and use some each() function to loop through the options.
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:
Each HTML Option element has a value and a text and some more attributes.
A simple for loop can be used
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
The most concise solution is this:
Array.apply
calls theArray
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,
Will create a proper array containing the elements of any "array-like" object
A
.To get all the values into an array:
Fiddle: http://jsfiddle.net/garreh/64pyb/1/
Well you can use a for loop, not much shorter but more ugly;
Then again it's a shame you're not using a library like jQuery. You could do:
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);
1 to quickly convert a collection to an array.So a crossbrowser way to convert a nodeList collection to array would be:
[edit] Nowadays (ES2015 and up) we can use
Array.from([arraylike object])
.1 or
Array.prototype.slice.call([some collection])
select.options is not an array, it is a NodeList which shares some of the features of an array and so can be described as array like. a NodeList doesn't have the methods that an Array has, but you can call or apply those methods to it. In your case you can call the join method like this:
Alternatively you could convert the NodeList into a true Array with a similar technique