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
(computing, graphical user interface) Multiple selection; the ability to have more than one item selected at the same time.
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/
$("#go").click(function(){ var textToAppend = ""; var selMulti = $("#selMulti option:selected").each(function(){ textToAppend += (textToAppend == "") ? "" : ","; textToAppend += $(this).text(); }); $("#result").html(textToAppend); });
One line style:
$("#selMulti option:selected").map(function(){return this.text}).get().join(', ');
Output:
"Option 1, Option 2"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With