Select2 4.0 - Push new entry after creation
Asked Answered
M

1

7

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?

Malacostracan answered 15/3, 2015 at 8:17 Comment(0)
I
21

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
Ionosphere answered 16/3, 2015 at 23:10 Comment(2)
This does not work for me on v4. Options removed, but .trigger('change') does not re-draw and pick up new optionsMythologize
awesome thanks @kevin after trying everything this worked for meLewie

© 2022 - 2024 — McMap. All rights reserved.