Jquery 自动完成,如果没有找到匹配项,则显示“no matches found”在下拉菜单中,但不允许关注它
这个问题说明了一切。我的 jquery 自动完成功能从我自己的 api 之一获取其来源。如果找不到任何匹配项,它只会返回“未找到匹配项”,然后显示在下拉列表中。当用户关注此内容时,框中的文本将更改为“未找到匹配项”。我想要做的是在下拉列表中显示“未找到匹配项”,但使其不可聚焦/可选择。这是我现在的代码:
$(document).ready(function() {
$("input#id_address").autocomplete({
delay: 300,
minLength: 3,
source: function(request, response) {
$.getJSON("/pin/cache/", {q:encodeURI(request.term)}, function(results) {
res = results.results;
response($.map(res, function(item) {
return {
label: item.address,
value: item.address,
lat: parseFloat(item.lat),
lng: parseFloat(item.lng)
}
}));
});
},
select: function(event, ui) {
if (ui.item.value == 'no matches found') {
return;
}
else {
$("#id_address").val(ui.item.value);
var pos = new google.maps.LatLng(ui.item.lat, ui.item.lng);
map.setCenter(pos);
map.setZoom(14);
placeMarker(pos);
}
},
});
});
如您所见,我正在使用 if else 循环来检查 select:function 中的“未找到匹配项”,如果选择了未找到匹配项,则不执行任何操作。但是,它仍然在焦点上填充文本“未找到匹配项”。我想要在找到匹配项时填充焦点文本的默认功能,但是当未找到匹配项时,下拉列表应该无法聚焦。有什么建议吗?
The question says it all. My jquery autocomplete gets its source from one of my own apis. If it cannot find any matches, it just returns "no matches found" which is then displayed in the dropdown. When the user focuses on this, the text in the box changes to "no matches found". What i want to do is display "no matches found" in the dropdown, but make it unfocusable/selectable. This is my code as of now:
$(document).ready(function() {
$("input#id_address").autocomplete({
delay: 300,
minLength: 3,
source: function(request, response) {
$.getJSON("/pin/cache/", {q:encodeURI(request.term)}, function(results) {
res = results.results;
response($.map(res, function(item) {
return {
label: item.address,
value: item.address,
lat: parseFloat(item.lat),
lng: parseFloat(item.lng)
}
}));
});
},
select: function(event, ui) {
if (ui.item.value == 'no matches found') {
return;
}
else {
$("#id_address").val(ui.item.value);
var pos = new google.maps.LatLng(ui.item.lat, ui.item.lng);
map.setCenter(pos);
map.setZoom(14);
placeMarker(pos);
}
},
});
});
As you can see, i am using an if else loop to check for "no matches found" in select:function to do nothing if no matches found is selected. However, it still fills in the text "no matches found" on focus. I want the default functionality of filling in the text on focus when matches are found, but when no matches are found, the dropdown should be unfocusable. Any suggestions ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一种可能的解决方案是在 select 的
focus()
处理程序上放置一个事件,检查文本“未找到匹配项”,如果是,则立即模糊它。One possible solution is to place an event on the select's
focus()
handler that checks for the text 'no matches found' and if so immediately blurs it.您可以使用 JavaScript 事件取消选择“不匹配”,也可以使用无法选择“不匹配”的 div 模拟下拉列表。
You can either use a JavaScript event to deselect the "no match" or use a div simulated droplist where "no match" cannot be selected.