Here I give you my example which contain --> Country flag, City, State, Country.
Here is my output.
Attach these two Cdn js or links.
js script
//for apend flag of country.
function formatState (state) {
console.log(state);
if (!state.id) {
return state.text;
}
var baseUrl = "admin/images/flags";
var $state = $(
' ' +state.text+ ''
);
return $state;
};
$(function(){
$("#itemSearch").select2({
minimumInputLength: 2,
templateResult: formatState, //this is for append country flag.
ajax: {
url: URL,
dataType: 'json',
type: "POST",
data: function (term) {
return {
term: term
};
},
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.name+', '+item.state.name+', '+item.state.coutry.name,
id: item.id,
contryflage:item.state.coutry.sortname
}
})
};
}
}
});
Expected JSON response.
[
{
"id":7570,
"name":"Brussels",
"state":{
"name":"Brabant",
"coutry":{
"sortname":"BE",
"name":"Belgium",
}
}
},
{
"id":7575,
"name":"Brussels",
"state":{
"name":"Brabant Wallon",
"coutry":{
"sortname":"BE",
"name":"Belgium",
}
}
},
{
"id":7578,
"name":"Brussel",
"state":{
"name":"Brussel",
"coutry":{
"sortname":"BE",
"name":"Belgium",
}
}
},
]