Jquery自动完成,如果找不到匹配项,则在下拉列表中显示“找不到匹配项”,但不允许关注它

时间:2011-05-06 18:43:20

标签: javascript jquery jquery-autocomplete jquery-ui-autocomplete

这个问题说明了一切。我的jquery autocomplete从我自己的apis获取源代码。如果找不到任何匹配项,则只返回“找不到匹配项”,然后显示在下拉列表中。当用户关注此时,框中的文本将更改为“找不到匹配项”。我想要做的是在下拉列表中显示“找不到匹配项”,但要使其无法对焦/可选择。这是我现在的代码:

$(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中的“找不到匹配项”,如果未找到匹配项,则不执行任何操作。但是,仍然会在焦点上填写“找不到匹配”的文字。我希望找到匹配项时在焦点上填写文本的默认功能,但是当找不到匹配项时,下拉列表应该是不可聚焦的。有什么建议吗?

2 个答案:

答案 0 :(得分:2)

一种可能的解决方案是在select的focus()处理程序上放置一个事件,检查文本“找不到匹配项”,如果是,则立即模糊它。

$("input#ip_address").focus(function(){
    if($(this).text()=="no matches found") {
        $(this).blur();
    }
});

答案 1 :(得分:0)

您可以使用JavaScript事件取消选择“不匹配”,也可以使用div模拟下拉列表,其中“无匹配”无法选择。