2014-09-23 91 views
0

如何在给出1个参数时(在与搜索字段不同的字段中)过滤列表。例如,用户指定group =“Test”并开始在#ContactPerson字段中搜索。我只想要显示“组”:“测试”的记录。jQuery自动完成:在值输入字段中缩小列表

("#ContactPerson").autocomplete({ 
       source: [{"value":"XYZ","name":"ZJL","group":"Test"},...] 
    ... 

这是我到目前为止已经试过,但它不工作:http://jsfiddle.net/71puvk59/

+0

[http://stackoverflow.com/questions/7734554/how-to-filter-your-jquery-autocomplete-data-while-typing#回答#7736994](http://stackoverflow.com/questions/7734554/how-to-filter-your-jquery-autocomplete-data-while-typing#answer-7736994) – Victor 2014-09-23 14:15:57

+0

我试图适应这个解决方案,我的问题,这是我尝试http://jsfiddle.net/71puvk59/当在第一个字段中输入测试时,只有1条记录可以显示在自动完成列表中。 – user3253002 2014-09-23 15:25:25

回答

1

根据this answer您可以覆盖搜索功能和适用所有的过滤器。

你的情况:

var source = [ 
    {"value": "JL", "name": "JL", "group": "Test"}, 
    {"value": "MV", "name": "MV", "group": "Family"} 
]; 

$('#ContactPerson').autocomplete({ 
    source: source, 
    search: function (oEvent, oUi) { 
     // get current input value 
     var sValue = $(oEvent.target).val(); 

     //groupValue 
     var groupValue = $("#group").val(); 

     // init new search array 
     var aSearch = []; 

     // for each element in the source array ... 
     $(source).each(function (iIndex, sElement) { 

      var groupFilterMatch = ((groupValue && sElement.group.indexOf(groupValue) != -1) || !groupValue); 
      var nameFilterMatch = sElement.name.indexOf(sValue) != -1; 

      // ... APPLY YOUR FILTERS HERE 
      //Example: filter group, if it is defined, and filter name 
      if (groupFilterMatch && nameFilterMatch) { 
       // add element 
       aSearch.push(sElement); 
      } 
     }); 

     // change search array 
     $(this).autocomplete('option', 'source', aSearch); 
    } 
}); 

http://jsfiddle.net/vcarvalho/91Lj5nxx/

+0

谢谢你,它的作品就像一个魅力!你知道如何让它不区分大小写吗? – user3253002 2014-09-24 07:48:03

+1

欢迎您。为了不区分大小写,将sElement.name.indexOf(sValue)'''改为'''sElement.name.toLowerCase()。indexOf(sValue.toLowerCase())''' – Victor 2014-09-24 14:01:46