Select2 4.0 - 创建后推送新条目 [英] Select2 4.0 - Push new entry after creation

查看:192
本文介绍了Select2 4.0 - 创建后推送新条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用Select2 4.0.0-rc.1几周(使用 ajax 适配器),我正试图找到一种推的方法初始化后的数据。

I have been using Select2 4.0.0-rc.1 for a couple of weeks (using the ajax adapter) and I am trying to find a way to "push" data after it has been initialized.

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

Within the dropdown list, I have the choice to


  • 在列表中选择一个条目(使用 ajax

  • 添加一个免费条目(使用 createTag

  • 添加新条目

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

If I select "add a new entry", I can fill out a form, and once saved, the new data must be shown as a selected entry.

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

If I push data using select2_existing.select2( { data: data } ).val( 4 ); it works, but ajax call does not work anymore.

我必须


  1. destroy select2

  2. 重新创建

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

Which will then allow me to have my new data and ajax adapter working.

可以不用create-> data-> destroy-> create cycle?

It is possible to do this without the create->data->destroy->create cycle?

推荐答案

你应该可以通过创建一个新选择的选项一个新的<选项> 标记,其中包含您要显示的信息。

You should be able to push a new selected option by creating a new <option selected> tag with the information you are looking to display.

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

一旦你追加这个< option> 到原来的< select> ,你将需要触发更改事件,以便Select2(和其他组件) )知道价值已经改变。

Once you append this <option> to the original <select>, you are going to need to trigger the change event so Select2 (and other components) are aware that the value changed.

$element.trigger("change");

所以在JavaScript中将它们放在一起

So putting it all together in 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

这篇关于Select2 4.0 - 创建后推送新条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆