从多个选择中用逗号分隔每个值 [英] separate each value with comma from multiple select
本文介绍了从多个选择中用逗号分隔每个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个<select multiple='multiple'
,我需要在div或页面的其他部分中显示所选的值.
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);
});
如果选择选项1和2,结果将是:
If you select the option 1 and 2, the result will be:
Option 1Option 2
我需要的是:
Option 1, Option 2
谢谢
推荐答案
您需要将元素映射到数组,然后将它们联接:
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(", "));
});
- http://api.jquery.com/jQuery.map/
- http://api.jquery.com/jQuery.map/
这篇关于从多个选择中用逗号分隔每个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文