JQuery autocomplete source from another js function

I have a jquery autocomplete function whose source is computed from another function based on request.term , so I cannot figure out how to set the source property correctly.

Autofill

 $( "#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, for example response = [ city1, city2, city3 ]; but autocomplete just launches the β€œLoader Icon” and nothing happens, there is no error in the log.

Can I say how to set the source from another js function?

+4
source share
3 answers

The source function has two parameters, the request and the callback, as soon as the response returns, 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

+7
source

In your anonymous callback, you need to return the return value of init(searchParam) .

Just change:

 init(searchParam); 

To:

 return init(searchParam); 
0
source

Example:

 source: function (request, response) { // Contains var searchString = request.term, array = []; // OPTIONS array.push('test 1'); array.push('foo'); array.push('var'); response(array); } 
0
source

Source: https://habr.com/ru/post/1501896/


All Articles