Javascript 从多个选择中用逗号分隔每个值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7915018/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
separate each value with comma from multiple select
提问by Ricardo Binns
I have a <select multiple='multiple'
and I need to show the selected value in a div or some other part of the page.
我有一个<select multiple='multiple'
,我需要在 div 或页面的其他部分显示选定的值。
I did this but the string is all smushed together. How can I separate each value with a comma?
我这样做了,但字符串都被弄乱了。如何用逗号分隔每个值?
I made a live examplewith what I have so far.
Or if you prefer, here is the code:
或者,如果您愿意,这里是代码:
html:
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:
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:
如果选择选项 1 和 2,结果将是:
Option 1Option 2
Option 1Option 2
What I need is:
我需要的是:
Option 1, Option 2
Option 1, Option 2
Thanks
谢谢
回答by Andy E
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: //jsfiddle.net/AcfUz/
回答by Kamil Lach
$("#go").click(function(){
var textToAppend = "";
var selMulti = $("#selMulti option:selected").each(function(){
textToAppend += (textToAppend == "") ? "" : ",";
textToAppend += $(this).text();
});
$("#result").html(textToAppend);
});
回答by Luis Hernandez
One line style:
一种线条样式:
$("#selMulti option:selected").map(function(){return this.text}).get().join(', ');
Output:
输出:
"Option 1, Option 2"