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 ?
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.
$("input#ip_address").focus(function(){
if($(this).text()=="no matches found") {
$(this).blur();
}
});
You can either use a JavaScript event to deselect the "no match" or use a div simulated droplist where "no match" cannot be selected.
精彩评论