Select2 4.0 - Push new entry after creation

Frederic picture Frederic · Mar 15, 2015 · Viewed 7.3k times · Source

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?

Answer

Kevin Brown picture Kevin Brown · Mar 17, 2015

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