【问题标题】:How to hide some text on options in select2 dropdown?如何在 select2 下拉菜单中隐藏选项上的一些文本?
【发布时间】:2020-02-26 12:42:59
【问题描述】:

我在这样的 select2 下拉列表中有一个产品列表。

<option>Product A [Barcode]</option>
<option>Product A [Barcode]</option>
<option>Product A [Barcode]</option>
<option>Product A [Barcode]</option>

现在 我想从选项中隐藏条形码,但如果输入了条形码,我希望搜索能够找到产品。我试过了

<option>Product A <span style='display:none;'>[Barcode]</span></option>

但没有成功。无法在文档中找到答案。请帮忙。

【问题讨论】:

  • 在寻求帮助之前显示您的尝试。
  • 在评论之前仔细阅读我尝试过的问题
  • 你的答案在哪里?还是说问题?

标签: javascript jquery html css jquery-select2


【解决方案1】:

选项元素内部不能有任何子元素,因此您可以将条形码值移动到选项的“值”属性中。然后定义 select2 匹配器函数以搜索选项值。

https://select2.org/searching

$('#mySelect').select2({
  matcher: function(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; }

    // check for both value and text
    var searchTarget = params.term.toLowerCase();
    if (data.text.toLowerCase().indexOf(searchTarget) > -1 || data.id.toLowerCase().indexOf(searchTarget) > -1) {
        return $.extend({}, data, true);
    }
    //
    return null;
}
});

结果是这样的:

https://jsfiddle.net/scarabs/canrx12k/

【讨论】:

    猜你喜欢
    • 2018-08-18
    • 2015-09-19
    • 2014-07-09
    • 2016-01-15
    • 2018-10-14
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    相关资源
    最近更新 更多