Select2 4.0 - 创建后推送新条目

Fre*_*ric 7 javascript jquery-select2 jquery-select2-4

我已经使用Select2 4.0.0-rc.1几周了(使用ajax适配器),我试图在初始化之后找到一种"推送"数据的方法.

在下拉列表中,我可以选择

  • 选择列表中的条目(使用ajax)
  • 添加免费条目(使用createTag)
  • 添加新条目

如果我选择"添加新条目",我可以填写表格,一旦保存,新数据必须显示为选定条目.

如果我使用select2_existing.select2( { data: data } ).val( 4 );它推送数据有效,但ajax呼叫不再起作用.

我已经到了

  1. 销毁select2
  2. 重新创造它

这将允许我让我的新数据和ajax适配器工作.

没有create-> data-> destroy-> create cycle就可以做到这一点?

Kev*_*own 19

您应该能够通过创建包含<option selected>您要显示的信息的新标记来推送新选择的选项.

<option value="id" selected="selected">text</option>
Run Code Online (Sandbox Code Playgroud)

将此附加<option>到原始文件后<select>,您将需要触发change事件,以便Select2(和其他组件)知道值已更改.

$element.trigger("change");
Run Code Online (Sandbox Code Playgroud)

所以把它放在JavaScript中

var $element = $("select"); // the element that Select2 is initialized on

var $option = $("<option selected></option>"); // the new base option
$option.val(newOption.id); // set the id
$option.text(newOption.text); // set the text

$element.append($option); // add it to the list of selections
$element.trigger("change"); // tell Select2 to update
Run Code Online (Sandbox Code Playgroud)