jQuery UI: Autocomplete - How do I search multiple values within an array?
Asked Answered
R

1

7

If you take a look at the following JS: (Live: http://jsfiddle.net/RyanWalters/dE6T3/2/)

var projects = [
    {
        value: "jquery",
        label: "jQuery",
        desc: "the write less, do more, JavaScript library",
        icon: "jquery_32x32.png"
    },
    {
        value: "jquery-ui",
        label: "jQuery UI",
        desc: "the official user interface library for jQuery",
        icon: "jqueryui_32x32.png"
    },
    {
        value: "sizzlejs",
        label: "Sizzle JS",
        desc: "a pure-JavaScript CSS selector engine",
        icon: "sizzlejs_32x32.png"
    }
];


$("#autocomplete").autocomplete({
    source: function(request, response){
        var matcher = new RegExp( $.ui.autocomplete.escapeRegex( request.term ), "i" );
        response( $.grep( projects, function( value ) {
            value = value.value || value.desc || value.icon;
            return matcher.test( value );
        }) );
    }
});

I'm trying to make the Autocomplete search the value, desc, and icon fields in the projects array. However, when I enter values into the search box, I can only search the value field. The desc and icon fields get completely ignored.

How can I make it so that I can search for text in any of the three fields?

Rattail answered 2/4, 2012 at 16:43 Comment(1)
couldn't you just "return matcher.test(value.value) || matcher.test(value.desc) || matcher.test(value.icon);" ?Manganin
T
11
value = value.value || value.desc || value.icon;

This will set value to the 1st "thuthy" value (which will always be value.value).

Try something like this:

response($.grep(projects, function(value) {
    return matcher.test(value.value) || matcher.test(value.desc) || matcher.test(value.icon);
}));
Teleology answered 2/4, 2012 at 16:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.