You need to transform the object you are getting back into an array in the format that jQueryUI expects.
You can use $.map
to transform the dealers
object into that array.
$('#dealerName').autocomplete({
source: function (request, response) {
$.getJSON("/example/location/example.json?term=" + request.term, function (data) {
response($.map(data.dealers, function (value, key) {
return {
label: value,
value: key
};
}));
});
},
minLength: 2,
delay: 100
});
Note that when you select an item, the "key" will be placed in the text box. You can change this by tweaking the label
and value
properties that $.map
's callback function return.
Alternatively, if you have access to the server-side code that is generating the JSON, you could change the way the data is returned. As long as the data:
label
property, a value
property, or both, orIn other words, if you can format the data like this:
[{ value: "1463", label: "dealer 5"}, { value: "269", label: "dealer 6" }]
or this:
["dealer 5", "dealer 6"]
Then your JavaScript becomes much simpler:
$('#dealerName').autocomplete({
source: "/example/location/example.json"
});