0

I'm using the JQuery UI autocomplete plugin (cached version) with JQuery-UI 1.11.1

Due to some server-side changes in the JSON I am using as source, I need to adapt my code.

Here is an example of my JSON:

[{
        "name": "Varedo"
    }, {
        "name": "Varena"
    }, {
        "name": "Varenna"
    }, {
        "name": "Varese"
}]

produced by an URL with this style: [url]/?name=vare

Since the GET variable is different from the default one ("term"), I already adapted my code for the custom request as suggested here:

$(function () {
  var cache = {};
  $("#searchTextField").autocomplete({
    minLength: 3,
    source: function (request, response) {
        var term = request.term;

        if (term in cache) {
            response(cache[term]);
            return;
        }

        $.getJSON("[url]", {
            name: request.term
        }, function (data, status, xhr) {
            cache[term] = data;
            response(data);
        });
    }
  });
});

However I need to also adapt the code in order to use a custom JSON value (the default is "value" http://api.jqueryui.com/autocomplete/#option-source) which is in my case is "name" (as you can see from the JSON).

How can I do that?

At the moment this is what I get from the autocomplete:

enter image description here

So I guess I am somehow giving as response JS Objects and not strings.

Thanks in advance.

1 Answer 1

1

Currently you're saving the response as it is into your cache object, which is not valid format for jQuery UI autocomplete. You should convert the data into proper format digestable for autocomplete.

Either you should pass an array of strings, or an array of objects having label and value properties.

Since the response only contains name properties, you can convert it into an array of strings using jQuery map() method and save it in cache variable as follows:

$("#searchTextField").autocomplete({
    minLength: 3,
    source: function (request, response) {
        var term = request.term;
        if (term in cache) {
            response(cache[term]);
            return;
        }

        $.getJSON("[url]", {
            name: request.term
        }, function (data, status, xhr) {
            cache[term] = $.map(data, function (obj) { // returns array of strings
                return obj.name
            });
            // return the new array rather than original response
            response(cache[term]);
        });
    }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.