Search code examples
jquerysearchliveerase

Ajax jquery searcher


Hello I recently coded this script with a help from some tutorials. The "problem" is that i want to be able to manually inserting names. As it is now if i type in a name witch does not exsist in db, and click away of the input field, it erases the text i typed in automaticly. I wan't the manually typed in text to be there and the suggestions div must fade out if a user clicks away of the input or uses tab.

<script type="text/javascript">
    function lookup(inputString) {
        if(inputString.length == 0) {
            // Hide the suggestion box.
            $('#suggestions').hide();
        } else {
            $.post("../autofill_institution.php", {queryString: ""+inputString+""}, function(data){
                if(data.length > 0) {
                    $('#suggestions').show();
                    $('#autoSuggestionsList').html(data);
                }
            });
        }
    } // lookup

    function fill(thisValue) {
            $('#inputString').val(thisValue);
            setTimeout("$('#suggestions').hide();", 200);
    }
</script>

Solution

  • To hide the suggestion list when the input looses focus you can do something like this

    $("idoftheinputfield").on("blur",function(e){
        $('#suggestions').hide()
    })
    

    It leaves me pondering why your input field is getting cleared when the focus is lost. Anyways if you want to retain the manually typed value you can tweak it a bit like this:

    $("idoftheinputfield").on("blur",function(e){
        var mycurrentvalue = $(this).val();
        $(this).val(mycurrentvalue);
        $('#suggestions').hide()
    })
    

    Hope this helps..