jwinn
jwinn

Reputation: 1125

jQuery UI autocomplete - using multi-dimensional array value in 'source', cache example

I am trying to modify this example of jQuery UI to accept the 2-dimensional JSON data. http://jqueryui.com/demos/autocomplete/#remote-with-cache

    var cache = {}, lastXhr;
    $( "#birds" ).autocomplete({
        minLength: 2,
        source: function( request, response ) {
            var term = request.term;
            if ( term in cache ) {
                response( cache[ term ] );
                return;
            }

            lastXhr = $.getJSON( "search.php", request, function( data, status, xhr ) {
                cache[ term ] = data;
                if ( xhr === lastXhr ) {
                    response( data );
                }
            });
        }
    });

How would I modify this to use the 'name' value in JSON data like this:

[{"name":"TEST1","slug":"blah-blah"},{"name":"TEST","slug":"example-slug-here"}]

Upvotes: 1

Views: 5233

Answers (1)

Andrew Whitaker
Andrew Whitaker

Reputation: 126072

The autocomplete widget expects data in the following format:

The local data can be a simple Array of Strings, or it contains Objects for each item in the array, with either a label or value property or both. The label property is displayed in the suggestion menu. The value will be inserted into the input element after the user selected something from the menu. If just one property is specified, it will be used for both

(emphasis mine)

This doesn't mean you can't use a remote source that doesn't respond with that format; you can massage the data to fit those requirements before calling the supplied response function.

With that in mind, I would modify the example for your case as follows:

lastXhr = $.getJSON( "search.php", request, function( data, status, xhr ) {
    cache[ term ] = $.map(data, function(item) {
        return {
            label: item.name,
            value: item.name,
            slug: item.slug,
            name: item.name
        };
    });
    if ( xhr === lastXhr ) {
        response( data );
    }
});

This should make the results show up properly (and caching should still work just fine). For another example of this, check out the remote JSONP example.

Upvotes: 5

Related Questions