2016-09-30 66 views
2

我有以下代碼 -jQuery的自動完成(devbridge)lookupFilter搜索多個屬性

$(function() { 

var fruits = [ 
    { value: 'Apple',id: '123', data: 'Apple' }, 
    { value: 'Pear', id: '543', data: 'Pear' }, 
    { value: 'Carrot', id: '123', data: 'Carrot' }, 
    { value: 'Cherry', id: '234', data: 'Cherry' }, 
    { value: 'Banana', id: '543', data: 'Banana' }, 
    { value: 'Radish', id: '3423', data: 'Radish' } 
]; 

    $("#autocomplete").autocomplete({ 
     lookup: fruits, 
     onSelect: function (suggestion) { 
      alert('You selected: ' + suggestion.value + ', ' + suggestion.data); 
     }, 
    }); 
}); 

我想基於「價值」和「ID」既做搜索。有lookupFilter函數,但我不知道如何使用它。這裏是原始腳本 - https://www.devbridge.com/sourcery/components/jquery-autocomplete/ 這裏是一些similer問題 - jQuery autocomplete (devbridge) search from beginning
請幫助!

回答

0

你可以嘗試用下面的代碼:

$(function() { 

var fruits = [ 
    { value: 'Apple',id: '123', data: 'Apple' }, 
    { value: 'Pear', id: '543', data: 'Pear' }, 
    { value: 'Carrot', id: '123', data: 'Carrot' }, 
    { value: 'Cherry', id: '234', data: 'Cherry' }, 
    { value: 'Banana', id: '543', data: 'Banana' }, 
    { value: 'Radish', id: '3423', data: 'Radish' } 
]; 

    $("#autocomplete").autocomplete({ 
     lookup: fruits, 
     onSelect: function (suggestion) { 
      alert('You selected: ' + suggestion.value + ', ' + suggestion.data); 
     }, 
     lookupFilter: function (suggestion, query, queryLowerCase) { 
      return suggestion.value.toLowerCase().indexOf(queryLowerCase) < -1 || suggestion.id.toLowerCase().indexOf(queryLowerCase) < -1; //checking with both id as well as value 
     } 
    }); 
}); 

注:我不能對此進行測試代碼,但我相信它應該爲你工作。

+0

沒有Vijay..Not工作。 –

+0

謝謝...我改變了><,它的工作。 –

+0

您確定自己喜歡'suggestion.value.toLowerCase()。indexOf(queryLowerCase)<-1'。如是;那麼我會更新答案,以便其他人可以參考它 – vijayP

0

lookupFilter:function (suggestion, query, queryLowerCase) {}用於本地查找的過濾功能。默認情況下,它會進行部分字符串匹配(不區分大小寫)。

代碼:

var fruits = [{value: 'Apple',id: '123',data: 'Apple'}, {value: 'Pear',id: '543',data: 'Pear'}, {value: 'Carrot',id: '123',data: 'Carrot'}, {value: 'Cherry',id: '234',data: 'Cherry'}, {value: 'Banana',id: '543',data: 'Banana'}, {value: 'Radish',id: '3423',data: 'Radish'}]; 
 

 
$('#autocomplete').autocomplete({ 
 
    lookup: fruits, 
 
    onSelect: function(suggestion) { 
 
     console.log('You selected: ' + suggestion.value + ', ' + suggestion.data); 
 
    }, 
 
    lookupFilter: function(suggestion, query, queryLowerCase) { 
 
     var id = suggestion.id, 
 
      value = suggestion.value.toLowerCase(); 
 
     return id.indexOf(query) === 0 || value.indexOf(queryLowerCase) === 0; 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.devbridge-autocomplete/1.2.26/jquery.autocomplete.min.js"></script> 
 

 
<input type="text" name="fruit" id="autocomplete"/>