我有一个自动完成功能,可以过滤本地json以将结果返回到文本框,但是在选择位置时,自动完成功能不会填充文本框。我尝试按照文档添加select
方法,但它会破坏我的功能。我应该在哪里将select
包含在我的代码库中?
自动填充功能:
$('#autocomplete').autocomplete({
minLength: 1,
source: function(request, response) {
var data = $.grep(suggestion, function(value) {
return value.city.substring(0, request.term.length).toLowerCase() == request.term.toLowerCase(); // Here the suggestion array is filtered based on what the user has typed. User input will be captured in the request.term
});
response(data); // this will return the filtered data which will be attached with the input box.
}
}).data( "ui-autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "ui-autocomplete-item", item )
.append( "<a>" + item.city + "," + item.country + "</a>" )
.appendTo( ul ); // here we are creating and appending appending element based on the response object we got after filtering
};
});
数据
var suggestion =
[
{"id":"1","name":"Goroka","city":"Goroka","country":"Papua New Guinea","iata":"GKA","icao":"AYGA","latitude":"-6.081689","longitude":"145.391881","altitude":"5282","timezone":"10","dst":"U","tz":"Pacific/Port_Moresby"}
,
{"id":"2","name":"Madang","city":"Madang","country":"Papua New Guinea","iata":"MAG","icao":"AYMD","latitude":"-5.207083","longitude":"145.7887","altitude":"20","timezone":"10","dst":"U","tz":"Pacific/Port_Moresby"}
,
{"id":"3","name":"Mount Hagen","city":"Mount Hagen","country":"Papua New Guinea","iata":"HGU","icao":"AYMH","latitude":"-5.826789","longitude":"144.295861","altitude":"5388","timezone":"10","dst":"U","tz":"Pacific/Port_Moresby"}
,
{"id":"4","name":"Nadzab","city":"Nadzab","country":"Papua New Guinea","iata":"LAE","icao":"AYNZ","latitude":"-6.569828","longitude":"146.726242","altitude":"239","timezone":"10","dst":"U","tz":"Pacific/Port_Moresby"}
,
{"id":"5","name":"Port Moresby Jacksons Intl","city":"Port Moresby","country":"Papua New Guinea","iata":"POM","icao":"AYPY","latitude":"-9.443383","longitude":"147.22005","altitude":"146","timezone":"10","dst":"U","tz":"Pacific/Port_Moresby"}
]
答案 0 :(得分:2)
选择可以放在您的案例中的源之前或之后,只要它作为属性保留在自动完成对象中。您可以按照以下示例:
$('#autocomplete').autocomplete({
minLength: 1,
source: function (request, response) { ... },
select: function (event, ui) {
event.preventDefault();
// [...] your code here
return false;
}
}).data( "ui-autocomplete" )._renderItem = function( ul, item ) { ... };