Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery autocomplete, if no matches found display "no matches found" in dropdown but dont allow focus on it

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 ?

like image 716
tapan Avatar asked Nov 04 '22 22:11

tapan


1 Answers

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();
    }
});
like image 63
ThePsion5 Avatar answered Nov 12 '22 17:11

ThePsion5