Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery autocomplete source from another js function

I have a Jquery autocomplete function whose source is calculated from another function based on request.term so i can not figure how to set source property right.

Autocomplete:

$( "#finder_city" ).autocomplete({
    source: function(request){
        var searchParam  = request.term;
        init(searchParam);
    },
    minLength: 2,
});

My function:

function init(query) {
//lot of code 
return response;

}

My function returns valid data, like response = [ city1, city2, city3 ]; but autocomplete just start "Loader icon" and nothing happens, no err in log.

Can anybody say how to set source from another js function ?

like image 880
lesnick Avatar asked Mar 22 '23 10:03

lesnick


1 Answers

The source function has two params, request and a callback, once the response comes back you need to call the callback

$( document ).ready(function() {

    $( "#finder_city" ).autocomplete({
        source: function(request, callback){
            var searchParam  = request.term;
            init(searchParam, callback)
        },
        minLength: 2
    });
});

function init(query, callback) {
    ymaps.geocode(query, { results: 5 }).then(function (res) {

        var response = [];
        if (res.geoObjects.get(0) == null) {

        }
        else if (res.geoObjects.get(1) == null){
            response = [
                res.geoObjects.get(0).properties.get('text')
            ];
        }
        else if (res.geoObjects.get(2) == null){
            response = [
                res.geoObjects.get(0).properties.get('text'),
                res.geoObjects.get(1).properties.get('text')
            ];
        }
        else if (res.geoObjects.get(3) == null){
            response = [
                res.geoObjects.get(0).properties.get('text'),
                res.geoObjects.get(1).properties.get('text'),
                res.geoObjects.get(2).properties.get('text')
            ];
        }
        else if (res.geoObjects.get(4) == null){
            response = [
                res.geoObjects.get(0).properties.get('text'),
                res.geoObjects.get(1).properties.get('text'),
                res.geoObjects.get(2).properties.get('text'),
                res.geoObjects.get(3).properties.get('text')
            ];
        }
        else {
            response = [
                res.geoObjects.get(0).properties.get('text'),
                res.geoObjects.get(1).properties.get('text'),
                res.geoObjects.get(2).properties.get('text'),
                res.geoObjects.get(3).properties.get('text'),
                res.geoObjects.get(4).properties.get('text')
            ];
        }
        callback(response);
    });
}

Demo: Fiddle

like image 123
Arun P Johny Avatar answered Apr 09 '23 18:04

Arun P Johny