使用 jQuery 的 select2 向多选添加值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16914926/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:03:03  来源:igfitidea点击:

Adding values to a multiple select with jQuery's select2

jqueryselectionjquery-select2multiple-selectmultipleselection

提问by Sean Kenny

I'm using the select2jQuery plugin on a <select>with multiple="multiple". I need to addvalues to the selected list (i.e. not to all the options, but to the selected options, without adding a new option).

我在withselect2上使用jQuery 插件。我需要向所选列表添加值(即不是向所有选项添加值,而是向所选选项添加值,而不添加新选项)。<select>multiple="multiple"

I know I can set the selected options with this:

我知道我可以用这个设置选定的选项:

$("#the_select").select2("val", "the_option_value"); 

Or, for multiple selections:

或者,对于多项选择:

$("#the_select").select2("val", ["an_option_value","another_option_value"]); 

However, is there a way I can add selected optionsto the list (i.e. make an option selected) without removing the others?

但是,有没有一种方法可以将选定的选项添加到列表中(即选择一个选项)而不删除其他选项?

回答by Sean Kenny

You should be able to use this:

你应该能够使用这个:

$("#the_select").append($('<option>', {value:"NEWVAL", text: "New Option Text"}));

It will append the new option item to the end of the list.

它将新的选项项目附加到列表的末尾。

HTH

HTH

Edit

编辑

Take 2 :) - I tried this in chrome dev tools over on the select2 page. It works (I added "WA" and Washingtonappeared.

采取 2 :) - 我在 select2 页面上的 chrome 开发工具中尝试了这个。它有效(我添加了“WA”并Washington出现了。

var selectedItems = $("#the_select").select2("val");
selectedItems.push("NEWITEMVAL");   // I used "WA" here to test.
$("#the_select").select2("val", selectedItems);

Or as a one liner:

或者作为一个班轮:

$("#the_select").select2("val", $("#the_select").select2("val").concat("NEWITEMVAL"));

回答by Shai Efrati

This is how i do it:

这就是我的做法:

      $("#the-select")
        .val($("#the-select")
          .val()
          .concat([array_of_existing_values]));
      $("#the-select")
        .trigger("change");

HTH

HTH