I have a jQuery Select2 control that uses AJAX to populate:
To get dynamic tagging to work with ajax, here's what I did.
Select2 version 3.5
This is easy in version 3.5 because it offers the createSearchChoice hook. It even works for multiple select, as long as multiple: true and tags: true are set.
HTML
JS
$('input[name="locations"]').select2({
tags: true,
multiple: true,
createSearchChoice: function(term, data) {
if (!data.length)
return { id: term, text: term };
},
ajax: {
url: '/api/v1.1/locations',
dataType: 'json'
}
});
The idea here is to use select2's createSearchChoice hook which passes you both the term that the user entered and the ajax response (as data). If ajax returns an empty list, then tell select2 to offer the user-entered term as an option.
Demo: https://johnny.netlify.com/select2-examples/version3
Select2 version 4.X
Version 4.X doesn't have a createSearchChoice hook anymore, but here's how I did the same thing.
HTML
JS
$('select[name="locations"]').select2({
ajax: {
url: '/api/v1.1/locations',
dataType: 'json',
data: function(params) {
this.data('term', params.term);
return params;
},
processResults: function(data) {
if (data.length)
return {
results: data
};
else
return {
results: [{ id: this.$element.data('term'), text: this.$element.data('term') }]
};
}
}
});
The ideas is to stash the term that the user typed into jQuery's data store inside select2's data hook. Then in select2's processResults hook, I check if the ajax response is empty. If it is, I grab the stashed term that the user typed and return it as an option to select2.
Demo: https://johnny.netlify.com/select2-examples/version4