Select2 - Ajax Selection Fails to Render Item

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.

Answer №1

To ensure that the correct value is displayed when selected, you must include a templateSelection.

templateSelection: function(data) {
   return data.customerName
},

var customers = [{
    id: 1,
    customerName: 'Lebron',
    stockName: 'IBM',
    customerType: 'person'
  },
  {
    id: 2,
    customerName: 'Nicole',
    stockName: 'CIA',
    customerType: 'dog'
  }, {
    id: 3,
    customerName: 'Antuan',
    stockName: 'FR3',
    customerType: 'envelope'
  }
]

$("#customerSelect").select2({
  dropdownAutoWidth: true,
  templateResult: iconUser,
  templateSelection: function(data) {
    return data.customerName
  },
  minimumInputLength: 0,
  placeholder: "-- Select a customer --",
  data: customers,
});


function iconUser(userDetails) {
  return $("<span><i class=\"fa-solid fa-" + userDetails.customerType + "\"></i> " + userDetails.customerName + " - " + userDetails.stockName + "</span>");
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="542731383137206614607a657a647926377a64">[email protected]</a>/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2754424b424453156713091609170a55440917">[email protected]</a>/dist/js/select2.min.js"></script>

<select class="form-control" id="customerSelect" style="width: 200px !important;"></select>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Selecting a variable ID triggers a dropdown menu

I am facing an issue with my image grid page. I want a drop-down to appear when any image is clicked, but the current code only works for a specific id. Although the code functions correctly, it is limited by its specificity. CSS: .wide { width:50px; } . ...

What is the best way to create a line graph with D3.js in order to display data that is obtained from a server-side source?

I am trying to access data from a server side link, which is as follows: The data I want to retrieve is in JSON format and looks like this: {"Id":466,"Name":"korea", "Occurren ...

Problem with manual initialization and overriding angular services during configuration stage

Trying to make my Angular application work in live mode and prototype mode by overriding services. When the prototype mode is activated in the config, the bootstrap process is paused, mock service files are loaded, and then bootstrapping resumes. Below is ...

problem arises due to node.js not functioning correctly

Being new to server-side scripting, I decided to give it a try with a file called "hellonode.js". Unfortunately, whenever I try to launch this file, I encounter an issue. I use node and attempt to access the file within a folder named new This results in ...

Arranging Angular Array-like Objects

I am in possession of an item: { "200737212": { "style": { "make": { "id": 200001510, "name": "Jeep", "niceName": "jeep" }, "model": { "id": "Jeep_Cherokee", "name": "Cherokee", "nice ...

Is it possible to utilize AJAX requests within Web Workers?

Ensuring that the latest changes made by the user on my web application are saved to the database is crucial. To achieve this, I have a function that sends the data to the database when the user closes the page: window.onbeforeunload = sendData; However, ...

"Learn how to use JavaScript and jQuery to alphabetically sort the default td values in a table

This table and script are being used to alphabetically sort the data within the td tags: <button type=button>Sort Options</button> <table class="table-data"> <tr> <td class="filename">C</td> </tr> <t ...

Leveraging google transliteration within a Flex environment

Here is an illustration of how the Google transliteration feature can be utilized in specific HTML textboxes. I am looking to incorporate this same functionality for a Flex application. Is there a method through which this can be achieved? <html> ...

Storing a Vue JS component as a string in a variable and displaying it using that variable

I am currently working on a project where I need to implement the following code snippet: <template v-for="(element, k) in place.data.content"> <data_elements[element.name].component></data_elements[element.name].component> </te ...

Switched from btao to Buffer, however encountering a TypeError while trying to push to Vercel

I am currently working on an application in Next.js where I need to encode my image to base64. Initially, I used btao and it worked well until I tried deploying to Vercel, which resulted in an error stating that btao was undefined. After researching a solu ...

Transforming a canvas element into an image sans the use of toDataURL or toBlob

Recently, I developed a small tool which involves adding a canvas element to the DOM. Strangely, when trying to use toBlob or toDataURL, I encountered an issue with the canvas being tainted and received the error message (specifically in chromium): Uncaugh ...

Sizing labels for responsive bar charts with chart.js

I'm encountering a problem with my bar chart created using chart.js - the responsive feature works well for some elements but not all. Specifically, the labels on my bar chart do not resize along with the window, resulting in a strange look at smaller ...

jQuery AJAX is failing to pass variables in Firefox and Safari, yet it works perfectly fine in Chrome

html <li><a class="download-link" href="<?php echo $path_data;?>">Download</a></li> ajax $(function(){ $('.download-link').click(function() { var wall_id = <?php echo $wall_id;?>; //sto ...

What is the best way to limit the character display to a maximum of 30 in Vue.js?

My current goal involves achieving the following task. In a certain variable, I currently have this text: let text = 'hey this is a super long phrase' I am looking to utilize a label to showcase the text, but with only a limited number of char ...

Do Single Page Applications utilize HTML markup semantics within the JSON payload as well?

Exploring the architecture of single-page applications (SPAs). In SPAs, the MVC View returns JSON instead of HTML for updating data dynamically. This process involves using a template to iterate over <li>json-data-here</li>. However, what occu ...

Is there a way to bring in data from a .d.ts file into a .js file that shares its name?

I am in the process of writing JavaScript code and I want to ensure type safety using TypeScript with JSDoc. Since it's more convenient to define types in TypeScript, my intention was to place the type definitions in a .d.ts file alongside my .js fil ...

Most effective method for integrating a JS module across all browsers

I have created a robust library that I want to integrate into a different web project. This library handles all its dependencies and consists of js, css, and html files. My ideal scenario would be to package it as an npm module and simply use import to in ...

How to Safeguard Data in FormView on ASP.NET to Prevent Loss?

I am currently working on an ASP.NET application that includes a lengthy FormView for creating or updating jobs. One concern our customer has is the possibility of data loss if users forget to click 'Save' after making changes on the form. We hav ...

Ways to ensure a button is ready to be clicked

For my beginner chrome extension project, I am facing a specific situation that I need help with. Imagine a scenario where I have a website with a search button. When the button is clicked, two possibilities can arise: A search result appears with a butt ...

Tips for creating matter.js shapes using the "WebGLRenderer" feature in three.js?

While matter.js is typically used for 2D implementations and three.js focuses on 3D, I have a specific case where I need to combine the two technologies. I recently discovered that it is possible to include a target renderer for matter.js (https://github ...