我正在使用 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/