I have a Select2 input that is working great. The user can start typing and select an option from the dropdown menu and it adds a tag into the input field, they can also create their own tags thanks to the createSearchChoice
function.
My scenario is when a user types in a customer's name who already exists, it locks on, and I want it to populate the field with tags (usual suppliers). The user can then delete or add more tags if they want.
My code is:
$('#usualSuppliers').select2({
containerCssClass: 'supplierTags',
placeholder: "Usual suppliers...",
minimumInputLength: 2,
multiple: true,
placeholder: 'Usual suppliers...',
createSearchChoice: function(term, data) {
if ($(data).filter(function() {
return this.name.localeCompare(term) === 0;
}).length === 0) {
return {id: 0, name: term};
}
},
id: function(e) {
return e.id + ":" + e.name;
},
ajax: {
url: ROOT + 'Ajax',
dataType: 'json',
type: 'POST',
data: function(term, page) {
return {
call: 'Record->supplierHelper',
q: term
};
},
results: function(data, page) {
return {
results: data.suppliers
};
}
},
formatResult: formatResult,
formatSelection: formatSelection,
initSelection: function(element, callback) {
var data = [];
$(element.val().split(",")).each(function(i) {
var item = this.split(':');
data.push({
id: item[0],
title: item[1]
});
});
//$(element).val('');
callback(data);
}
});
How can I make it pre-populate the input with tags that come in from an Ajax request?
I managed to solve the issue thanks to this post:
Load values in select2 multiselect
By using trigger.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With