使用jquery自动完成功能搜索多个值

时间:2013-11-15 16:15:03

标签: jquery-ui jquery-autocomplete

您好我正在尝试让jQuery UI自动完成小部件工作,以便它从我的数组的多个属性中搜索匹配但是在我的代码中不起作用。 目前

如果我输入“coupe”,那就是“保时捷,奥迪,梅赛德斯”的回应。以同样的方式,我将能够键入'911'并作为响应“保时捷”接收。谢谢你的帮助。

$(function() {

var cars =
[
    {   "constructor" : "BMW", 
        "model": "Z3", 
        "type": "cabrio" },

    {   "constructor" : "Porsche", 
        "model": "911", 
        "type": "coupe" },

    {   "constructor" : "Audi", 
        "model": "A3", 
        "type": "coupe" },

    {   "constructor" : "Mercedes", 
        "model": "SL500", 
        "type": "coupe" }
];

    $("#quickFind").autocomplete({
        source: function(request, response){
            var matcher = new RegExp( $.ui.autocomplete.escapeRegex( request.term ), "i" );
            response( $.grep( cars, function( value ) {
            return matcher.test(value.constructor) || matcher.test(value.model) || matcher.test(value.type);
        }));
        }
    });

  });

1 个答案:

答案 0 :(得分:2)

在您的汽车数组的每个对象上都缺少"label" and "value" options,请看一下: http://jsfiddle.net/DLLVw/77/

$(function() {

var cars =
[
    {   
        "label" : "BMW - Z3 - cabrio",
        "value" : "BMWZ3",
        "constructor" : "BMW", 
        "model": "Z3", 
        "type": "cabrio" },

    {   
         "label" : "Porsche - 911 - coupe",
        "value" : "Porsche911",
        "constructor" : "Porsche", 
        "model": "911", 
        "type": "coupe" },

    {   "label" : "Audi - A3 - coupe",
        "value" : "AudiA3",

         "constructor" : "Audi", 
        "model": "A3", 
        "type": "coupe" },

    {   
        "label" : "Mercedes - SL500 - coupe",
        "value" : "mercedessl500",
        "constructor" : "Mercedes", 
        "model": "SL500", 
        "type": "coupe" }
];

    $("#quickFind").autocomplete({
        source: function(request, response){
            var matcher = new RegExp( $.ui.autocomplete.escapeRegex( request.term ), "i" );
            response( $.grep( cars, function( value ) {
            return matcher.test(value['constructor']) || matcher.test(value.model) || matcher.test(value.type);
        }));
        }
    });

  });