Jquery UI Autocomplete: search from multiple attributes of one array

Autocomplete accepts a third type of source, a function, that can provide data any way you see fit:

The third variation, a callback, provides the most flexibility and can
be used to connect any data source to Autocomplete. The callback gets
two arguments:

  • A request object, with a single term property, which refers to the value currently in the text input. For example, if the user enters
    “new yo” in a city field, the Autocomplete term will equal “new yo”.
  • A response callback, which expects a single argument: the data to suggest to the user. This data should be filtered based on the
    provided term, and can be in any of the formats described above for
    simple local data. It’s important when providing a custom source
    callback to handle errors during the request. You must always call the
    response callback even if you encounter an error. This ensures that
    the widget always has the correct state.

This means that you can write something like this

$( "#project" ).autocomplete({
    source: function (request, response) {
        // request.term is what you typed
        console.log(request.term); 

        //call response with an array containing the filtered data
        response([...]); 
    }
});

A simple solution to your problem:

function lightwell(request, response) {
    function hasMatch(s) {
        return s.toLowerCase().indexOf(request.term.toLowerCase())!==-1;
    }
    var i, l, obj, matches = [];

    if (request.term==="") {
        response([]);
        return;
    }

    for  (i = 0, l = projects.length; i<l; i++) {
        obj = projects[i];
        if (hasMatch(obj.label) || hasMatch(obj.desc)) {
            matches.push(obj);
        }
    }
    response(matches);
}

$( "#project").autocomplete({
    source: lightwell
});

And a Fiddle http://jsfiddle.net/FUZPN/5/

Leave a Comment