Phil R
Phil R

Reputation: 423

JQuery UI Autocomplete - Display and Search Different Data

I'm trying to make what should be a simple change to the way the jquery ui autocomplete operates.

Currently I am providing the source property with objects of the following format:

{label: "Display This", value: "Search This", other: "This is some other random data"}

As my example and title suggest, I would like to display different data in the drop down than what the user types in to search on. How is this possible? I'd rather not use Joe Schmoe's plugin.

Thanks!

Upvotes: 3

Views: 1732

Answers (2)

Andrew Whitaker
Andrew Whitaker

Reputation: 126052

Here's one way you could do this (assumes a local data source):

var source = [{label: "Display This", value: "Search This", other: "This is some other random data"}];

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

Example: http://jsfiddle.net/dHFk8/ (search "Search")

If you're using a remote data source, then you can perform whatever search logic you'd like in the server-side code.

Upvotes: 2

fehays
fehays

Reputation: 3167

You can implement an ajax call in your "source" method and in the success method of that call, you can create a map in the response(). And you can set the "label" and "value" properties:

This may work (untested):

// sample data returned from ajax call
var sampleData = [
    { label: 'test label', value: 'test value' },
    { label: 'test label1', value: 'test value1' },
    { label: 'test label2', value: 'test value2' },
    { label: 'test label3', value: 'test value3' }
];
response($.map(sampleData, function (item) {
    return {
        label: item.label,
        value: item.value
    }
}));

Upvotes: 0

Related Questions