簡體   English   中英

如何在select2下拉列表中隱藏選項上的一些文本?

[英]How to hide some text on options in select2 dropdown?

我在 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>

但沒有成功。 無法在文檔中找到答案。 請幫忙。

選項元素內部不能有任何子元素,因此您可以在選項的“值”屬性中移動條形碼值。然后定義 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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM