This drives me crazy! Why cant Select2 implement clear methods or examples on their page how to do simple CRUD manipulation on Select2 :)
i have a select2 which gets data from a ajax call.
<input id="valueg" type="hidden" style="width: 300px;" data-placeholder="Select a Conference" />
$("#valueg").select2({
data: conferences,
allowClear: true,
initSelection: function (element, callback) {
var data = { id: element.val(), text: element.val() };
callback(data);
}
}).on("change", function (e) {
// show data in separate div when item is selected
});
Can some one provide a clear method how to delete and add an item from the Select2.
For example:
I add an item via ajax call to db, and just want to append an option to Select2 and set it as selected.
I remove an item via ajax to db, and want to remove an option from Select2 and have no option selected.
I had the same issue. This is how i solved it
This has nothing to do with select2, manipulating the itself seems to work for me
I did it this way:
Hope that helps
From your example I can see that you attached Select2 plugin to hidden element. In addition you use Ajax call to populate results, so in this case if you need to add a new option to the list you simple call:
In case of using select element as a container the only way that I found is to reinitialize plugin with new options... Something like this:
In my case, the key thing to add after manipulating the underlying select is:
$selectlist.trigger("change");
//$selectlist is the underlying select element.Select2 works around the change event on a select, so calling "change" updates the option displayed in the select 2.
It is too late... but this is my solution for people that still have this problem: