JQuery - Multiple Select Options

2020-02-02 04:37发布

I am trying to grab all selected items in the following select multiple and separate them by a comma. The code is below:

<select id="ps-type" name="ps-type" multiple="multiple" size="5">
    <option>Residential - Wall Insulation</option>
    <option>Residential - Attic /Crawl Space Insulation</option>
    <option>Residential - Foundation Insulation</option>
    <option>Residential - Exterior Roof System</option>
    <option>Commercial - Wall Insulation</option>
    <option>Commercial - Air Barrier System (Walltite)</option>
    <option>Commercial - Roof System</option>
</select>

The result I am looking for is the following:

Residential - Wall Insulation, Commercial - Wall Insulation, ...

标签: jquery select
9条回答
做自己的国王
2楼-- · 2020-02-02 05:04

Try this:

    var List = new Array();
    $('#ps-type option:selected').each(function () {
       if ($(this).length) {
              var sel= {
                  name: $this.text()
              }
       }
       List.push(sel);
    });
    var result = List.join(', ');
查看更多
三岁会撩人
3楼-- · 2020-02-02 05:11

Add the values to an array and use join to create the string:

var items = [];
$('#ps-type option:selected').each(function(){ items.push($(this).val()); });
var result = items.join(', ');
查看更多
对你真心纯属浪费
4楼-- · 2020-02-02 05:11
var list = "";
$('#ps-type option:selected').each(function(){
  list += this.value + ", ";
});
return list.substr(0, list.length - 2);
查看更多
登录 后发表回答