I’m using the following code to fetch options from a database and populate a select2 on open. It works pretty well, but as soon as I start typing in the select2 search input box it also searches via the same ajax function. How can I just populate every time it opens, but then leave it there as long as it’s opened?
Also since I’m using it to create tags I lost the ability to auto-select the new tag when I attached the ajax part, so instead of typing and pressing enter to add a tag, it’s now stuck in search-land and I have to click on the newly created tag manually if I want it to be selected.
Any ideas?
function formatMenu (data) {
if (!data.id) { return data.text; }
var $data = $(
'<nobr>' + data.text + '</nobr>'
);
return $data;
};
$('select').select2({
templateSelection: formatMenu,
dropdownCssClass: 'select2-menu',
dropdownParent: $('#parent'),
placeholder: '-',
tags: true,
allowClear: true,
ajax: {
url: "?ajax=get_data,
dataType: 'json',
delay: 250,
data: function (params) {
return {
searchTerm: params.term
};
},
processResults: function (response) {
return {
results: response
};
},
cache: false
},
sorter: function(data) {
return data.sort(function (a, b) {
a = a.text.toLowerCase();
b = b.text.toLowerCase();
if (a > b) {
return 1;
} else if (a < b) {
return -1;
}
return 0;
});
},
createTag: function (params) {
return {
id: params.term,
text: params.term
}
}
});