Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript selecbox.options to array?

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?

like image 738
Rafael Herscovici Avatar asked May 26 '11 11:05

Rafael Herscovici


People also ask

How can I give an array as options to select element?

To set a JavaScript array as options for a select element, we can use the options. add method and the Option constructor. to add the select drop down. to select the select element with querySelector .

Can you convert number to array in JavaScript?

Typecast the integer into a string. Using the split() method to make it an array of strings. Iterate over that array using the map() method. Using the map() method returns the array of strings into an array of Integers.

Can we convert string to array in JavaScript?

The string in JavaScript can be converted into a character array by using the split() and Array. from() functions.

Can we convert object to array in JavaScript?

To convert an object to an array you use one of three methods: Object. keys() , Object. values() , and Object. entries() .


1 Answers

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.

like image 61
typeracer Avatar answered Sep 19 '22 17:09

typeracer