Chris Worrell Chris Worrell - 2 days ago 6
jQuery Question

jQuery UI autocomplete with JSON

Alright been racking my brain on this (im terrible at this) but yea ive tried reading all i can and still cant get it to work.

trying to do autocomplete with jquery ui

my json looks like this

{"dealers":
{
"1156":"dealer 1",
"1122":"dealer 2",
"1176":"dealer 3",
"1491":"dealer 4",
"1463":"dealer 5",
"269":"dealer 6"
}
}


i am trying to use this information as the source for autocomplete. i am getting the response object just fine I am just having trouble getting it in the right format so that I can place the "###" in a hidden field tied to the "value" which needs to be displayed as the portion of the drop down.

been trying a million different ways but a recent attempt was below

function ajaxCall() {
$.getJSON("/example/location/example.json?term=" + $('#dealerName').val(),
function(data) {
$.each(data.dealers, function(k, v) {
alert(k + ' : ' + v);
});
});
}

$('#dealerName').autocomplete({
source: ajaxCall,
minLength: 2,
delay: 100
});


Please and thank you much!

Answer

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:

  • Is an array of objects that have a label property, a value property, or both, or
  • Is a simple array of strings

In 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"
});
Comments