【问题标题】:How to display exact value from drop down?如何从下拉列表中显示确切的值?
【发布时间】:2022-01-17 08:16:09
【问题描述】:

我已经通过 select2 配置了我的选择,并且一切正常。

我使用 templateResult 和 formatState 方法将图标添加到我的下拉选项中。

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

但不会将任何内容更改为所选值(见下图)。

我如何确保所选值(在我的情况下为 EUR)与选项显示完全相同:欧元 (EUR)?

谢谢。

【问题讨论】:

    标签: jquery-select2 jquery-select2-4


    【解决方案1】:

    https://select2.org/selections 中描述的templateSelection 方法可以用来实现这一点,它可以传递templateResult 使用的相同函数。

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

    下面列出了示例国家及其国旗(不是货币)。

    // 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>

    【讨论】:

      猜你喜欢
      • 2020-07-10
      • 2019-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-07
      • 2020-12-01
      相关资源
      最近更新 更多