Question

I'm creating an auto complete search box. The suggestions have to disappear when the user clicks outside the search field.

The form input field:

<input type="text" name="naam_textbox" id="naam_textbox" class="field" autocomplete="off" onkeyup="suggest(this.value, 'naam');" onblur="fill();" />

The javascript code:

function suggest(inputString, veld){
if(veld == "naam") {
    if(inputString.length < 2) {
        $('#suggestions_naam').fadeOut();
    } else {
    $('#naam_textbox').addClass('load');
        var dropdown = $( '<div class="suggestionsBox" id="suggestions_naam" style="display: none;"><div class="suggestionList" id="suggestionsList_naam"> &nbsp; </div></div>' );
        if (inserted_naam == 0) {
            dropdown.insertAfter( "#naam_textbox" );
            inserted_naam = 1;
        }
        $.post("includes/homepage/autosuggest_naam.php", {queryString: ""+inputString+""}, function(data){
            if(data.length >0) {
                $('#suggestions_naam').fadeIn();
                $('#suggestionsList_naam').html(data);
                $('#naam_textbox').removeClass('load')
            }
        });
    }
}
}

function fill(thisValue, veld) {
    if(veld == "naam") {
        $('#naam_textbox').val(thisValue);
        setTimeout("$('#suggestions_naam').fadeOut();", 60);
    }
}

"fadeOut" makes the suggestions go away whenever the inputString is less then 2 characters, or when one of the suggestions is selected.

I need it also to fadeOut whenever someone clicks outside the input field (lose focus) or doesn't select a suggestion. To make it more clear, an image:

Suggestions should go away when user clicks on red dot

The suggestions should go away when a user clicks somewhere near the red dot for example. I can't get it to work, any help please?

Was it helpful?

Solution

Here is cause of the issue,

onblur="fill();" //no parameters

Whereas you method is

function fill(thisValue, veld) {   //2parameters
    if(veld == "naam") {
        $('#naam_textbox').val(thisValue);
        setTimeout("$('#suggestions_naam').fadeOut();", 60);
    }
}

MISSING TO PASS PARAMETERS and therefore it was not working.

so change it as

onblur = "fill(this.value, 'naam')"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top