[英]jquery autocomplete not filter and showing all results from json file
我有一個文本框,可根據名稱從JSON文件中搜索城市,但它不起作用。 例如,當我搜索Antalia時,我的自動填充結果只會返回JSON文件中列出的所有城市:
這是我的JSON文件:
[
{ "label" : "Tehran", "hotelid" : 1203548.0 },
{ "label" : "Antalya", "hotelid" : 1168092.0 }
]
這是我的jQuery自動完成代碼:
<input autocomplete="off" name="_root.route.start.country" class="autocomplete-hint select" data-auto-complete-minlength="1" type="text" onFocus="searchCountry(this)" placeholder="Departure">
<script type="text/javascript">
function searchCountry(a) {
$(function() {
var cache = {};
$(a).autocomplete({
appendTo: ".countrys",
change: function (event, ui) {
if (ui.item == null || ui.item == undefined) {
$(a).val("");
$(a).empty();
$(a).next("#loading").hide();
} else {
var position = $(".countrys").position(),
left = position.left, top = position.top;
$(".countrys > ul").css({
left: left + 20 + "px",
top: top + 4 + "px"
});
}
},
minLength: 1,
select: function (event, ui) {
// Set autocomplete element to display the label
this.value = ui.item.label;
$(this).closest("tr").find(".countryid").val(ui.item.hotelid);
$(this).closest("tr").find(".countryid").next(".countryid").val(ui.item.hotelid);
// Store value in hidden field
$('#hidden_field').val(ui.item.id);
$('#hidden_field1').empty().text(ui.item.label);
// Prevent default behaviour
return false;
},
source: function( request, response ) {
$(a).next("#loading").show();
var term = request.term;
if (term in cache) {
response(cache[term]);
return;
}
$.getJSON( "jsonloadi.bc", request, function( data, status, xhr ) {
$(a).next("#loading").hide();
cache[ term ] = data;
response( data );
});
}
});
});
}
</script>
因為您正在加載整個JSON文件並返回它,而沒有任何查詢過濾。
$(a).next("#loading").show(); // move loading animation here
$.getJSON("jsonloadi.bc", request, function(data, status, xhr) {
// YOU NEED TO FILTER DATA FIRST!
var filtered = data.filter(function(hotel) {
return hotel.label.indexOf(term) !== -1;
});
cache[term] = filtered;
$(a).next("#loading").hide();
response(filtered);
});
您還應該移動$(a).next("#loading").show();
如我的示例所示,因為在返回緩存的響應時不需要加載動畫,並且還可以將該動畫無限期地保留在那里。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.