Reputation: 3246
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
Upvotes: 22
Views: 34679
Reputation: 628
One line style:
$("#selMulti option:selected").map(function(){return this.text}).get().join(', ');
Output:
"Option 1, Option 2"
Upvotes: 2
Reputation: 4629
$("#go").click(function(){
var textToAppend = "";
var selMulti = $("#selMulti option:selected").each(function(){
textToAppend += (textToAppend == "") ? "" : ",";
textToAppend += $(this).text();
});
$("#result").html(textToAppend);
});
Upvotes: 4
Reputation: 344585
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/
Upvotes: 38