Select2 4.0 - 创建后推送新条目

Select2 4.0 - Push new entry after creation

本文关键字:新条目 创建 Select2      更新时间:2023-09-26

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

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

  • 在列表中选择一个条目(使用 ajax
  • 添加免费条目(使用 createTag
  • 添加新条目

如果我选择"添加新条目",我可以填写表格,保存后,新数据必须显示为所选条目。

如果我使用select2_existing.select2( { data: data } ).val( 4 );推送数据,它可以工作,但ajax调用不再有效。

然后我必须

  1. 销毁选择2
  2. 重新创建它

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

是否可以在没有创建->数据>销毁->创建循环的情况下做到这一点?

您应该能够通过使用要显示的信息创建新的<option selected>标记来推送新的选定选项。

<option value="id" selected="selected">text</option>

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

$element.trigger("change");

所以把它们放在 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