Select2 4.0 - Push new entry after creation

大城市里の小女人 提交于 2019-11-27 09:07:39

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>

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");

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!