Javascript 选择2 4.0-创建后推送新条目
我已经使用Select2 4.0.0-rc.1好几周了(使用Javascript 选择2 4.0-创建后推送新条目,javascript,jquery-select2,jquery-select2-4,Javascript,Jquery Select2,Jquery Select2 4,我已经使用Select2 4.0.0-rc.1好几周了(使用ajax适配器),我正在试图找到一种在数据初始化后“推送”数据的方法 在下拉列表中,我可以选择 在列表中选择一个条目(使用ajax) 添加一个免费条目(使用createTag) 添加新条目 如果我选择“添加新条目”,我可以填写表格,保存后,新数据必须显示为所选条目 如果我使用select2\u existing.select2({data:data}).val(4)推送数据它可以工作,但是ajax调用不再工作 那么我必须 销毁sel
ajax
适配器),我正在试图找到一种在数据初始化后“推送”数据的方法
在下拉列表中,我可以选择
- 在列表中选择一个条目(使用
)ajax
- 添加一个免费条目(使用
)createTag
- 添加新条目
select2\u existing.select2({data:data}).val(4)推送数据代码>它可以工作,但是ajax
调用不再工作
那么我必须
销毁select2
重新创建它
这将允许我的新数据和ajax
适配器工作
不需要创建->数据->销毁->创建周期就可以执行此操作。您应该能够通过创建一个新的
标记来推送一个新选择的选项,该标记包含您要显示的信息
<option value="id" selected="selected">text</option>
因此,将其全部放在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
var$element=$(“选择”);//Select2在其上初始化的元素
变量$option=$(“”);//新的基本选项
$option.val(newOption.id);//设置id
$option.text(newOption.text);//设置文本
$element.append($option);//将其添加到选择列表中
$element.trigger(“更改”);//告诉Select2更新
这在v4上对我不起作用。选项已删除,但.trigger('change')不会重新绘制和拾取新选项在尝试了所有这些对我有效的方法后,非常感谢@kevin
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