Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

separate each value with comma from multiple select

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

like image 928
Ricardo Binns Avatar asked Oct 27 '11 11:10

Ricardo Binns


People also ask

What does select multiple mean?

(computing, graphical user interface) Multiple selection; the ability to have more than one item selected at the same time.


3 Answers

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/

  • http://api.jquery.com/jQuery.map/
like image 189
Andy E Avatar answered Oct 04 '22 02:10

Andy E


$("#go").click(function(){      var textToAppend = "";      var selMulti = $("#selMulti option:selected").each(function(){            textToAppend += (textToAppend == "") ? "" : ",";            textToAppend += $(this).text();                 });      $("#result").html(textToAppend); }); 
like image 45
Kamil Lach Avatar answered Oct 04 '22 03:10

Kamil Lach


One line style:

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

Output:

"Option 1, Option 2"
like image 33
Luis Hernandez Avatar answered Oct 04 '22 03:10

Luis Hernandez