2017-02-20 43 views
1

對不起,如果這是一個重複的問題,但我不明白其他人的答案。我使用的是Twitter Bootstrap Ajax Typeahead插件(https://github.com/biggora/bootstrap-ajax-typeahead/),用於從來自SQL查詢的數據中搜索電子郵件。這是我使用的一個PHP文件的代碼,我使用人們的電子郵件作爲valueField和人名作爲displayField,並且效果很好。bootstrap-typeahead的顯示字段使用多個值

inputSearch.typeahead({ 
    ajax: { 
    url: urlAjax + '?requete=rechercheannuaire', 
    displayField: "description", 
    valueField: "id", 
    triggerLength: 2, 
    method: "get", 
    loadingClass: "loading-circle", 
    preProcess: function(data){ 
     if(data.type === "error") 
     { 
      return false; 
     } 

     return data.datas;  
    } 
    }, 
    onSelect: function(data){ 
    //alert("assez tot"); 
    data.text = data.value; 
    //console.log(data); 
    $("#chercherinvite").val(data.text); 

     return data; 
    } 

}); 

的問題是,我必須能夠搜索到「迪雅爾丹」以及「杜花園」,我不能找到一種方法,多值賦給displayField。如果有人能夠解釋typeahead是如何工作的,我會很感激,我不理解這些文檔。

回答

0

根據插件文檔,您不能將多個值分配給displayField選項。但是,您可以重寫事件。

通過快速查找source code of bootstrap-ajax-typeahead後,我們可以發現「匹配器」事件用作向用戶顯示或不顯示值的過濾器。

爲了能夠匹配「Du jardin」和「Dujardin」,我們必須操縱字符串。在這裏,我建議你:

  1. 刪除任何音調符號的字符
  2. 刪除所有非單詞字符(除了[A-ZA-Z0-9 _])
  3. 刪除任何下劃線
  4. 設置字符串變爲小寫

要做#1,我建議你使用這個fantastic script by rdllopes

我寫了一個POC。這裏是JSON源(稱爲 「source.json」):

[ 
    { "id": 1, "name": "[email protected] - Jean Du Pont"}, 
    { "id": 2, "name": "[email protected] - Jean Dupont"}, 
    { "id": 3, "name": "[email protected] - Jéan Dupônt"}, 
    { "id": 4, "name": "[email protected] - Michel Bridge"} 
] 

這裏是我用於匹配元素的腳本:

$('#search').typeahead({ 
    // Our source is a simple JSON file 
    ajax: 'source.json', 

    // Display field is a list of names 
    displayField: 'name', 

    // And value field a list of IDs 
    valueField: 'id', 

    matcher: function(item) 
    { 
     // For both needle and haystack, we : 
     // 1. Remove any diacritic character 
     // 2. Remove any non-word character (all except [A-Za-z0-9_]) 
     // 3. Remove any underscore 
     // 4. Set the string to lowercase 
     var needle = removeDiacritics(this.query).replace(/[^\w]/gi, '').replace('_', '').toLowerCase(); 
     var haystack = removeDiacritics(item).replace(/[^\w]/gi, '').replace('_', '').toLowerCase(); 

     // Does the needle exists in haystack? 
     return ~haystack.indexOf(needle); 
    } 
});