Using Tags to filter but selecting an original option leaves the tag as an appending option


#1

What I’m trying to achieve:

  • A default list of options
  • A user can type to filter options
  • A user can type and add an option that does not exist in the original list.

It appears that when searching and clicking on a result that is not the tag, the tag is still added to the as an option. I would expect that the searched value/tag should be cleared when this happens.

Here is the code I use to init Select2:
$(‘select#EmailTo’).select2({
multiple: true,
tags: true,
createTag: function(params) {
var term = $.trim(params.term);
if (term === ‘’) {
return null;
}
return {
id: term,
text: term
}
}
});
$(‘select#EmailTo’).on(‘change’,
function () {
var $selectedOptions = $(‘option[data-select2-tag=“true”]’);
$.each($selectedOptions,
function () {
var $o = $(this);
$o.prop(‘selected’, true);
});
});

Does anyone know of a way I can use tags to filter, and only add them to the list of options when the filtered value is the selected value?

Thanks in advance!


#2

Welp - not sure if it is a bug, but I made a little work around:

$(‘select#EmailTo’).on(‘select2:select’,
function(e) {
var data = e.params.data;
var $selectedOptions = $(’#EmailTo option[data-select2-tag=“true”]:last’);
if (e.params.originalEvent === undefined) {
$.each($selectedOptions,
function () {
var $o = $(this);
if ($o.val() !== data.text) {
$o.remove();
}
});
}

			});

If the selected option doesn’t match the searched option, delete the searched option :smiley: