I am not able to work with select2 version 4.0 for developing an option to suggest tags items stored in database through ajax call after writing few letters(2,3 letters) of desired tag name.
Because of the change of the version initSelection
method of previous versions does not exists anymore. It thows an error "No select2/compat/initSelection".
Here is code that I used with previous versions:
$('.addTags').select2({
placeholder: "Problem Tags",
allowClear: true,
minimumInputLength: 2,
tags: true,
createSearchChoice: function (term, data) {
if ($(data).filter(function () {
return this.text.localeCompare(term) === 0;
}).length === 0) {
return {
id: term,
text: term
};
}
},
initSelection: function (element, callback) {
var tags = element.val().split(",");
var data = [];
for (var i = 0; i < tags.length; i++) {
data.push({ id: tags[i], text: tags[i] });
}
callback(data);
},
multiple: true,
ajax: {
type: 'GET',
url: "/Problem/GetTags",
dataType: 'json',
data: function (term, page) {
return {
term: term,
page_limit: 15
};
},
results: function (data, page) {
return { results: data.tags };
}
}
});
Working with Select2 4.0.0 version you have to change createSearchChoice
to createTag
:
createTag: function (params) {
var term = $.trim(params.term);
if (term === '') {
return null;
}
return {
id: term,
text: term,
newTag: true // add additional parameters
}
}
then initSelection
is generally not needed (see https://select2.org/upgrading/migrating-from-35#removed-the-requirement-of-initselection).
In ajax option change results
handler to processResults
:
processResults: function (data, page) {
return { results: data.tags };
},
Here is a jsfiddle for example: https://jsfiddle.net/beaver71/bhodkpav/