2016-09-20 58 views
0

我想在我的select2數據項中添加一個文本屬性並能夠搜索它。select2在兩個屬性上搜索

例如,我有這樣的數據:

var data : 
[ 
    { id : 1, text : 'Item 1', description : 'Long text description for item 1' }, 
    { id : 2, text : 'Item 2', description : 'Long text description for item 2' }, 
    { id : 3, text : 'Item 3', description : 'Long text description for item 3' }, 
] 

我想選擇2到能夠找到的結果,如果我輸入,在輸入的描述屬性值匹配的文本。

是否可以做到這一點?

預先感謝您。

+0

選擇二可與一個有效的HTML標記的基本選擇。你將在哪裏存儲文本信息,因爲select只有值和描述? –

+0

我不知道,也許在'data-description' attribut – T00rk

+0

那麼你也必須編寫你自己的插件版本。一個版本,它將從select和自定義搜索選項的html結構中設置select2標記中的data- *屬性。此功能目前不受支持。對於標準選擇的基本搜索選項,我看到了一個很好的答案,但它被刪除了 –

回答

0

的解決方案是創建一個自定義的匹配,並使用它像這樣

$('.select2-typeahead').select2 
({ 
    data : 
    [ 
     { id : 1, text : 'Item 1', description : 'Long text description for item 1' }, 
     { id : 2, text : 'Item 2', description : 'Long text description for item 2' }, 
     { id : 3, text : 'Item 3', description : 'Long text description for item 3' }, 
    ], 
    matcher : function(params, data, item) 
    { 
     if ($.trim(params) === '') 
     { 
      return data; 
     } 

     if(data.toLowerCase().indexOf(params.toLowerCase()) > -1 || item.description.toLowerCase().indexOf(params.toLowerCase()) > -1) 
     { 
      return data; 
     } 

     return null; 
    }