使用JQuery格式化multiselect的值

使用JQuery格式化multiselect的值,jquery,html,twitter-bootstrap-3,Jquery,Html,Twitter Bootstrap 3,我在HTML中定义了以下multiselect: <div class="col-sm-10"> <select multiple class="form-control" id="los" name="los[]"> {leden} </select> </div> 这给了我multiselect的所有文本条目。但是,我无法设置该列表的格式。是否有任何方法可以创建包含选定选项1、选定选项2、…、选定选项x的字符串,

我在HTML中定义了以下multiselect:

<div class="col-sm-10">
    <select multiple class="form-control" id="los" name="los[]">
       {leden}
    </select>
</div>
这给了我multiselect的所有文本条目。但是,我无法设置该列表的格式。是否有任何方法可以创建包含选定选项1、选定选项2、…、选定选项x的字符串,以便在以下情况下使用:

    btn.addEventListener("click", function(e){
            showBSModal({
                title: "Controleer gegevens",
                body: "De mail zal naar de volgende groep gestuurd worden:<br>" +
                $('#aan option:selected').text() + "<br><br>" +
                "De mail wordt ook naar de volgende personen gestuurd:<br>" +
                $('#email').val() + *The string of all selected items*
            )}
   };

如果您希望进行自定义,请尝试:

 var mySelectedOptions = '';
 ("#los option:selected").each(function(){
    mySelectedOptions += $(this).text()+", ";
 }

然后只需对格式化字符串使用mySelectedOptions。

短更改事件演示如何获取选定元素,映射其值的数组,然后将它们连接到一个字符串中,并在它们之间加上“,”

$'los'。关于'change',函数{ console.log$'option:selected',this.mapfunction{ 返回this.innerHTML; }.get.join','; }; 一 二 三 四
您需要循环并使用逗号将所选选项转换为字符串

$( "#los" ).change(function() {
    var str = "";
    // loop all your selected options
    $( "#los option:selected" ).each(function() {
      // concat to a string with comma
      str += $( this ).text() + ", ";
    });
    // trim comma and white space at the end of string
    str = str.slice(0, -2);
  });

变量str将具有格式化的选定选项

对于任何有同样问题的人:这个答案解决了它。我唯一的补充是,我在函数作用域之外声明了变量str,因为其他函数无法访问它:谢谢!
$( "#los" ).change(function() {
    var str = "";
    // loop all your selected options
    $( "#los option:selected" ).each(function() {
      // concat to a string with comma
      str += $( this ).text() + ", ";
    });
    // trim comma and white space at the end of string
    str = str.slice(0, -2);
  });