Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jqueryUI autocomplete with extra data?

Using jQueryUI Autocomplete

I'd like to attach some other data onto a results list from the box. For instance, my data set might look like:

[
    {
        "name": "John's wild bacon emporium",
        "code": "BACON"
    },
    {
        "name": "Jill and Jack's well",
        "code": "WELL"
    },
    {
        "name": "Herp and derp",
        "code": "HD"
    }
]

But the jQueryUI docs say it wants a flat array of strings.

Users are going to search by name, never the code (lets pretend). More importantly, I want to be able to access what that code is when looking at select: function(event, ui) {/*...*/}, be it through the data-xxx, or some other voodoo. I'd like to avoid using a second list to match up strings against label contents (lets pretend we can have duplicate names somehow and users will never get confused), I just want to glue the code data onto the name label.

A question like this was asked in 2008, but since then the plugin doesn't have .result() anymore.

like image 302
Incognito Avatar asked Dec 13 '22 13:12

Incognito


1 Answers

But the jQueryUI docs say it wants a flat array of strings.

Actually:

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.

So as long as your data has at least a value property for each object in the array, the widget can handle it:

[
    {
        "name": "John's wild bacon emporium",
        "code": "BACON",
        "value": "Bacon",
    },
    {
        "name": "Jill and Jack's well",
        "code": "WELL"
        "value": "Well"
    },
    {
        "name": "Herp and derp",
        "code": "HD",
        "value": "Herp"
    }
]

The user's query will be matched against the value property of each object (notice that label is not required; only specify it if you want to show something different in the list of autocomplete options than the value).

You can access the extra data about the item inside the select event handler:

select: function(event, ui) {
    alert(ui.item.code); // Access the item's "code" property.
}

Hope that helps. Here's a simple example: http://jsfiddle.net/vR3QH/. I removed the name property and am just using the value property instead. Every time an item is selected, input elements are updated with values of properties belonging to the selected item.

like image 135
Andrew Whitaker Avatar answered Dec 15 '22 04:12

Andrew Whitaker