Tuesday 15 January 2013

javascript - Getting values from an HTMLCollection to a string -


I am trying to capture the selected values ​​of the multi-select dropdown and later change them to a string for manipulation I am doing At the moment I have the following code:

HTML:

  & lt; Select ID = "genreList" multi = "multiple" name = "Adjuster []" style = "width: 150px; font-size: 10pt;" & Gt; & Lt; Option value = "Action" & gt; Action & lt; / Option & gt; & Lt; Option value = "comedy" & gt; Comedy & lt; / Option & gt; & Lt; Option value = "Fictional" & gt; Fantasy & lt; / Option & gt; & Lt; Option value = "horror" & gt; Horror & lt; / Option & gt; & Lt; Option value = "suspense" & gt; Mystery & lt; / Options & gt; & Lt; Option value = "non-fiction" & gt; Non-fiction & lt; / Options & gt; & Lt; Option value = "duration" & gt; Period & lt; / Options & gt; & Lt; Option value = "romance" & gt; Romance & lt; / Options & gt; & Lt; Option value = "Sci-Fi" & gt; Sci-Fi & lt; / Option & gt; & Lt; Option value = "thriller" & gt; Thriller & lt; / Options & gt; & Lt; / Select & gt; & Lt; / P & gt; & Lt; P & gt; Input type = "button" onclick = "newComic ()" value = "add comic" id = "btnAddComic" style = "font-size: 10pt; width: 150px; height: 40px;" & Gt; & Lt; / P & gt;  

Javascript:

  & lt; Script & gt; Function newComic () {var elem = document.query selector ("# genreList"). Selected option; Var arr = [] .slice.call (elem); Var styles = arr.join (','); Window.alert (style); } & Lt; / Script & gt;  

The warning window is currently outputting the following:

[Object HTMLOptionElement, Object HTMLOptionElement, ...]

Where '. .. 'represents any further hypothetical options.

What do I want to produce as 'styles', for example, instead of 'Action, Romance, Thriller'.

Do any help.

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

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

No comments:

Post a Comment