Select2搜索与标签相关的关键字

时间:2019-10-02 11:22:48

标签: jquery search jquery-select2 keyword tagging

我目前正在开发一个使用select2加载货币的货币转换应用程序。

我希望用户能够通过输入国家/地区来查找货币。例如:

  • 如果对美国->美元的搜索应该出现
  • 如果要搜索“ 西班牙”,“ 意大利->欧元”

我一直在浏览Select2文档,但是找不到如何在货币标签中添加相关关键字。

请参见下面的代码:

<select id="to" class="js-example-templating" onchange="convertCurrencyRight()" onkeyup="convertCurrencyRight()" >
        <option value="USD" selected>USD </option>
        <option value="EUR"  >EUR </option>
</select>

http://abc.dfe.com/myWebService.svc?wsdl

有什么解决方法吗?

谢谢

1 个答案:

答案 0 :(得分:0)

使用自定义matcherdata()函数

$(".select").select2({
  matcher: matchCustom
});

function matchCustom(params, data) {
  // If there are no search terms, return all of the data
  if ($.trim(params.term) === '') {
    return data;
  }

  // Do not display the item if there is no 'text' property
  if (typeof data.text === 'undefined') {
    return null;
  }

  // `params.term` should be the term that is used for searching
  // `data.text` is the text that is displayed for the data object
  if (data.text.toUpperCase().indexOf(params.term.toUpperCase()) > -1) {
    return data;
  }

  // custom search using lookup data
  if ($(data.element).data('lookup').toUpperCase().indexOf(params.term.toUpperCase()) > -1) {
    return data;
  }

  // Return `null` if the term should not be displayed
  return null;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.full.min.js"></script>

<select class="select" style="width: 200px">
  <option value="USD" data-lookup="America" selected>USD </option>
  <option value="EUR" data-lookup="Spain, Italy">EUR </option>
</select>