I can't find any native method unfortunately. But if you're interested in simple "workarounds", maybe this get you closer:
$('.select2').select2({
tags: true,
tokenSeparators: [",", " "],
createTag: function (tag) {
return {
id: tag.term,
text: tag.term,
// add indicator:
isNew : true
};
}
}).on("select2:select", function(e) {
if(e.params.data.isNew){
// append the new option element prenamently:
$(this).find('[value="'+e.params.data.id+'"]').replaceWith('<option selected value="'+e.params.data.id+'">'+e.params.data.text+'</option>');
// store the new tag:
$.ajax({
// ...
});
}
});
DEMO
[EDIT]
(Small update: see @Alex comment below)
The above will work only if the tag is added with mouse. For tags added by hitting space or comma, use change
event.
Then you can filter option
with data-select2-tag="true"
attribute (new added tag):
$('.select2').select2({
tags: true,
tokenSeparators: [",", " "]
}).on("change", function(e) {
var isNew = $(this).find('[data-select2-tag="true"]');
if(isNew.length && $.inArray(isNew.val(), $(this).val()) !== -1){
isNew.replaceWith('<option selected value="'+isNew.val()+'">'+isNew.val()+'</option>');
$.ajax({
// ... store tag ...
});
}
});
DEMO 2
:select
event? So every time something is selected, you get it like this:$(selector).on("select2:select", function (e) { console.log(e.params.data); });
. This indeed does not make a difference between existing vs. new objects, but its a start. – MonnetcreateTag
isn't an event but a method that's overridden. It looks like the developer responded to your question on Gitlab about this the next day (github.com/select2/select2/issues/3063) - it would have been nice had you updated your question or provided an answer. For others, the develop suggested listening for theselect2:selected
event; I've found that achange
event is fired also. – Interplead