Select2 4.0 - Push new entry after creation

那年仲夏 提交于 2019-11-26 17:48:22

问题


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

  • select an entry in the list (using ajax)
  • add a free entry (using createTag)
  • add a new entry

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.

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

I have then to

  1. destroy select2
  2. re-create it

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

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


回答1:


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


来源:https://stackoverflow.com/questions/29058625/select2-4-0-push-new-entry-after-creation

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