jquery-select2jquery-select2-4

How to display exact value from drop down?


I have configured my select via select2 and things works quite well.

I have used templateResult with formatState approach to add the icon to my dropdown options.

$(".js-country-list").select2({
  templateResult: formatState
});

that however does not change anything to selected value (see image below).

How can I make sure that selected value (in my case EUR) would be displayed exactly same as option: Euro (EUR)?

Thanks.

enter image description here


Solution

  • The templateSelection method described at https://select2.org/selections can be used to achieve this, it can be passed the same function used by templateResult.

    $(".js-country-list").select2({
      templateResult: formatState,
      templateSelection: formatState
    });
    

    Example listing countries and their flags (not currencies) is incorporated below.

    // Template function which adds CSS flag and displays country name
    function flagTemplate(country){
      return $("<span class='flag-icon flag-icon-" + country.id + " '></span><span class='flag-text'>" + country.text + "</span>");
    }
    
    // Generate correct URL based on entered search term
    function generateUrl(params){
      if(params.term){
        return "https://restcountries.com/v3.1/name/" + params.term;
      } else {
        return "https://restcountries.com/v3.1/all";
      }
    }
    
    // Initialise select2 using flagTemplate function for both result and selection
    $('#countrySelect').select2({
      // Set template for results and selection
      templateResult: flagTemplate,
      templateSelection: flagTemplate,
      // Set placeholder text
      placeholder: 'Select country...',
      // Load country list from https://restcountries.com
      ajax: {
        url: generateUrl,
        cache: 250,
        dataType: "json",
        processResults: function(data) {      
          return {
            results: data
              .map(x => ({id: x.cca2.toLowerCase(), text: x.name.common}))
              .sort((a, b) => ('' + a.text).localeCompare(b.text))
          };
        }
      }
    });
    #countrySelect {
      width: 300px;
    }
    
    .flag-text {
      margin-left: 10px;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    
    <!-- Load flags using library https://github.com/lipis/flag-icons  -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/flag-icon-css/4.1.5/css/flag-icons.min.css" rel="stylesheet"/>
    
    <select id="countrySelect"><option></option></select>