Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
54
rated 0 times [  55] [ 1]  / answers: 1 / hits: 29812  / 9 Years ago, tue, march 17, 2015, 12:00:00

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:





    function newComic()
{
var elem = document.querySelector(#genreList).selectedOptions;
var arr = [].slice.call(elem);
var genres = arr.join(', ');
window.alert(genres);
}

 <select id=genreList multiple=multiple name=addGenre[]  style=width: 150px;font-size: 10pt;>
<option value=Action>Action</option>
<option value=Comedy>Comedy</option>
<option value=Fantasy>Fantasy</option>
<option value=Horror>Horror</option>
<option value=Mystery>Mystery</option>
<option value=Non-Fiction>Non-Fiction</option>
<option value=Period>Period</option>
<option value=Romance>Romance</option>
<option value=Sci-Fi>Sci-Fi</option>
<option value=Thriller>Thriller</option>
</select></p>

<p><input type=button onclick=newComic() value=Add Comic id=btnAddComic style=font-size: 10pt; width: 150px; height:40px;></p>





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.


More From » html

 Answers
9

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(', ');

[#67401] Monday, March 16, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
janettejordynm

Total Points: 550
Total Questions: 94
Total Answers: 98

Location: Senegal
Member since Fri, Aug 21, 2020
4 Years ago
janettejordynm questions
Tue, Nov 24, 20, 00:00, 4 Years ago
Sat, May 23, 20, 00:00, 4 Years ago
Mon, Apr 6, 20, 00:00, 4 Years ago
Tue, Feb 18, 20, 00:00, 4 Years ago
;