I am using select2 version 4 with multiple select and I support users adding new tags but I want to prevent people choosing a new tag if that tag already exists on my backend.
Right now if a user enters a tag that already exists and I have tags:true then it shows two items in the dropdown (the existing one and the new one). Here is an example:
as you can see, "testTag2" is a valid tag from my backend so it shows up in the selection but because of the templateResult function and the fact that tags:true it also shows up as a second item (making the user think they can select it as a new tag).
Is there anyway to only show the "NEW" tag choice in the dropdown, if that text is NOT listed in the dropdown as another option?
here is my javascript code:
function SetupAppTags() {
$("#Tags").select2({
theme: "classic",
width: "98%",
tags: true,
ajax: {
url: "/Tag/Search",
dataType: 'json',
delay: 300,
data: function(params) {
return { q: params.term };
},
processResults: function(data, params) {
return { results: data };
},
cache: false
},
escapeMarkup: function(markup) { return markup; },
minimumInputLength: 3,
templateResult: tagFormatResult,
templateSelection: tagSelectionResult
});
}
function tagFormatResult(tag) {
if (tag.loading) {
return "Loading . . . <img src='/Content/Images/ajax-loader.gif' />";
} else {
if (tag.name) {
var existsAlready = $("#Tags option[value='" + tag.id + "']").length > 0;
if (existsAlready) {
return null;
}
return tag.name;
}
var length = $('#tagsContainer .select2-selection__choice').filter(function () {
return $(this).attr("title").toUpperCase() === person.text.toUpperCase();
}).length;
if (length == 1) {
return null;
}
return tag.text + " [NEW]";
}
}