Reputation: 20785
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.
Upvotes: 4
Views: 4827
Reputation: 126082
But the jQueryUI docs say it wants a flat array of strings.
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.
Upvotes: 13