Getting values from an HTMLCollection to a string

alex494 picture alex494 · Mar 17, 2015 · Viewed 23.1k times · Source

I am attempting to grab the selected values of a multi-select dropdown and convert them into a single string for later manipulation. At the moment I have the following code:

The alert window is currently outputting the following:

[object HTMLOptionElement, object HTMLOptionElement, ...]

where '...' represents any further hypothetical options.

What I need is for 'genres' to output as, for example, 'Action, Romance, Thriller' instead.

Thanks in advance for any help.

Answer

James Montagne picture James Montagne · Mar 17, 2015

When you join the array, it is calling the "toString" of each element. In this case, they are DOM elements and return their type. You can use map first to create a new array of strings containing the value of each option:

http://jsfiddle.net/Lfx6r5sm/

var genres = arr.map(function(el){
    return el.value;
}).join(', ');