I setup a Select2 Object to work wit han ajax source data.
This is the Html
<select class="form-control" id="customerSelect" style="width: 200px !important;"></select>
This is the JS to initialize and fill the select
$("#customerSelect").select2({
dropdownAutoWidth: true,
templateResult: iconUser,
minimumInputLength: 3,
placeholder: "-- Select a customer --",
ajax: {
url : "/admin/ajax/orders.php",
type:'POST',
dataType: 'json',
delay: 250,
data: function (params) {
return {
searchTerm: params.term,
action: 'listCustomers',
isJs: true
};
},
processResults: function (result) {
return {
results: $.map(result['data'], function (item) {
return {
id: item.id,
customerName: item.customerName,
stockName: item.stockName,
customerType: item.customerType
}
})
};
}
}
});
And this is my template function, I add an icon in front of the text
function iconUser (userDetails) {
return $("<span><i class=\"fa-solid fa-"+userDetails.customerType+"\"></i> "+userDetails.customerName+" - "+userDetails.stockName+"</span>");
}
Everything works fine before the loading, the select shows up with the right placeholder
When I click on it, it load correctly the search results
but once I click on an item, any, it doesn’t appear anything on the select
Sorry, I insert only one image as new member I’ve limitations
Here’s the html code after I click on the select, it seems the rendered space is empty, even if the right element is populated (user_748)
<select class="form-control select2-hidden-accessible" id="customerSelect" style="width: 200px !important;" data-select2-id="select2-data-customerSelect" tabindex="-1" aria-hidden="true">
<option value="user_748" data-select2-id="select2-data-116-dhe1"></option>
</select>
<span class="select2 select2-container select2-container--default select2-container--below" dir="ltr" data-select2-id="select2-data-1-39br" style="width: 200px;">
<span class="selection">
<span class="select2-selection select2-selection--single" role="combobox" aria-haspopup="true" aria-expanded="false" tabindex="0" aria-disabled="false" aria-labelledby="select2-customerSelect-container" aria-controls="select2-customerSelect-container">
<span class="select2-selection__rendered" id="select2-customerSelect-container" role="textbox" aria-readonly="true"></span>
<span class="select2-selection__arrow" role="presentation">
<b role="presentation"></b>
</span>
</span>
</span>
<span class="dropdown-wrapper" aria-hidden="true"></span>
</span>
I tried to search in the forum and in the web, but with no luck