22

I have a <select multiple='multiple' and I need to show the selected value in a div or some other part of the page.

I did this but the string is all smushed together. How can I separate each value with a comma?

I made a live example with what I have so far.

Or if you prefer, here is the code:

html:

<select multiple='multiple' id="selMulti">
     <option value="1">Option 1</option>
     <option value="2">Option 2</option>
     <option value="3">Option 3</option>
     <option value="4">Option 4</option>    
</select>
<input type="button" id="go" value="Go!" />
<div style="margin-top: 10px;" id="result"></div>

js:

$("#go").click(function(){
     var selMulti = $("#selMulti option:selected").text();
     $("#result").text(selMulti);
});

If you select the option 1 and 2, the result will be:

Option 1Option 2

What I need is:

Option 1, Option 2

Thanks

Jeffrey Blake
  • 9,659
  • 6
  • 43
  • 65
Ricardo Binns
  • 3,228
  • 6
  • 44
  • 71

3 Answers3

38

You need to map the elements to an array and then join them:

$("#go").click(function(){
     var selMulti = $.map($("#selMulti option:selected"), function (el, i) {
         return $(el).text();
     });
     $("#result").text(selMulti.join(", "));
});

Working demo: http://jsfiddle.net/AcfUz/

Andy E
  • 338,112
  • 86
  • 474
  • 445
4
$("#go").click(function(){
     var textToAppend = "";
     var selMulti = $("#selMulti option:selected").each(function(){
           textToAppend += (textToAppend == "") ? "" : ",";
           textToAppend += $(this).text();           
     });
     $("#result").html(textToAppend);
});
Kamil Lach
  • 4,519
  • 2
  • 19
  • 20
2

One line style:

 $("#selMulti option:selected").map(function(){return this.text}).get().join(', ');

Output:

"Option 1, Option 2"
Luis Hernandez
  • 453
  • 5
  • 8