jquery - 使用 jQuery 的 select2 将值添加到多重选择

标签 jquery selection jquery-select2 multiple-select multipleselection

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

我知道我可以使用 this 设置所选选项:

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

或者,对于多项选择:

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

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

最佳答案

您应该能够使用这个:

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

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

HTH

编辑

Take 2 :) - 我在 chrome 开发工具的 select2 页面上尝试了这个。它有效(我添加了“WA”并且出现了华盛顿

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

或者作为单行:

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

关于jquery - 使用 jQuery 的 select2 将值添加到多重选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16914926/

相关文章:

ios - 如何知道我的 UITableView 中没有选择任何行?

jquery - Safari 渲染页面字体更细,页面上有 jQuery slider

javascript - 是否可以在 Ajax 语句中使用字符串来引用 json 对象?

jquery - 在使用 jQuery 将数据刷新到 div 时,它给出了重复的值

javascript - 在 contenteditable div 中突出显示的文本周围添加 html 标签

selection - bootstrap-vue 选择带有过滤器选项的组件?

jquery-select2 - 强制 select2-plugin 显示所有项目

jquery - 如何解决错误 "jQuery is not defined"?

javascript - jquery select2 如果在源中找不到,则将文本添加到源

jquery - python:html 编写器?