Reputation: 55
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 ?
Upvotes: 4
Views: 15701
Reputation: 18937
Example:
source: function (request, response) { // Contains
var searchString = request.term,
array = [];
// OPTIONS
array.push('test 1');
array.push('foo');
array.push('var');
response(array);
}
Upvotes: 0
Reputation: 388316
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
Upvotes: 7
Reputation: 141839
In your anonymous callback, you need to return the return value of init(searchParam)
.
Just change:
init(searchParam);
To:
return init(searchParam);
Upvotes: 0