Utilizing a Select2 Object for an ajax data source, the following HTML is used:
<select class="form-control" id="customerSelect" style="width: 200px !important;"></select>
The JavaScript code below initializes and populates 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
}
})
};
}
}
});
Below is the template function that adds an icon before the text:
function iconUser (userDetails) {
return $("<span><i class=\"fa-solid fa-"+userDetails.customerType+"\"></i> "+userDetails.customerName+" - "+userDetails.stockName+"</span>");
}
Despite correct loading of search results upon click, selecting an item does not display anything in the select box. Refer to the image below:
https://i.sstatic.net/FbQ7Q.png
Post selection, the rendered space in the HTML appears empty even though the element (user_748) is populated:
<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>
Efforts to find solutions online has been unsuccessful so far.