jquery从select生成一个分隔字符串


jquery generating a delimited string, from select

从下拉列表中,用户可以选择选项并单击按钮将该选项添加到文本框中。同时,我想将该文本添加到用"|"分隔符连接每个选项的隐藏字段中。

<select id="services" multiple>
        <option>Mobile</option>
        <option>Computer</option>
        <option>Electronic</option>
</select>
$( "#services-add" ).click(function() {
//here when this button clicked I want to add options to hidden field(already created) as string with deliminator 
}

这是我想附加文本的隐藏字段

<input type="hidden" name="value" value="" />

使用map将所有选定的数据收集到数组中,并使用attr 存储到隐藏字段

$("#services-add").click(function () {
    var val = $("#services option:selected").map(function () {
        return $(this).text();
    }).get();
     $("[type=hidden][name=value]").attr("value", val);
});

演示

$( "#services-add" ).click(function() 
{                                
var insertText =$("#services option:selected").map(function () {
        return this.value;
}).get().join('|');
$('#services-view').val(insertText);
});

演示:

http://jsfiddle.net/Npm6w/1/