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
ajax
)createTag
)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
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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With