tuna
tuna

Reputation: 6351

bootstrap typeahead autocomplete returns multiple from same value

I have the following jquery function that takes the source as a json from server. But when I run this script in client, As soon as i type, i get multiple from same value and it keeps increasing when I keep continue to enter keys.

function autocomplete(html_field, request_url, hidden_field){
    var map = {};
    var objects = [];
    $(html_field).typeahead({
    minlength: 3,
    source: function (query, process) {
        return $.get(request_url, { query: query }, function (data) {
            $.each(data, function(i, obj){
                map[obj.translations__name] = obj;
                objects.push(obj.translations__name);
            });
            return process(objects);
            });
    },
    updater: function (item) {
        $(hidden_field).val(map[item].id);
        return item;
        }
    });
}

Any ideas ?

Upvotes: 1

Views: 635

Answers (1)

Getz
Getz

Reputation: 4053

I think you have to empty your array objects before your .each() function, cause for each jquery call, the data are pushed into the array.

    source: function (query, process) {
        return $.get(request_url, { query: query }, function (data) {
            objects.splice(0, objects.length);
            $.each(data, function(i, obj){
                map[obj.translations__name] = obj;
                objects.push(obj.translations__name);
            });
            return process(objects);
            });

You can see here for empty an array: How do I empty an array in JavaScript?

Upvotes: 1

Related Questions