简体   繁体   中英

Autocomplete function not working

So I have this autocomplete in Javascript but its not fully working. The autocomplete list is not clickable so nothing gets filled into the textbox when you click an item from the list.

HTML:

<input type="text" name="naam_klant" size="20" id="naam_klant" onkeyup="lookup(this.value);" onblur="fill();" >    
<div class="suggestionsBox" id="suggestions" style="display: none;">
  <div class="suggestionList" id="autoSuggestionsList">
  </div>
</div>

Javascript:

function lookup(inputString)
{
  if(inputString.length == 0)
  {
    $('#suggestions').hide();
  }    
  else     
  {    
    $.post("sql_naam_klant.php", {queryString: ""+inputString+""}, function(data)    
    {   
      if(data.length >0)    
      {    
        $('#suggestions').show();    
        $('#autoSuggestionsList').html(data);
      }
    });
  }
}

function fill(thisValue) 
{
  $('.inputString').val(thisValue);
  setTimeout("$('.suggestions').hide();", 200);        
}

Query:

if(isset($_POST['queryString']))
{
  $queryString = $db->real_escape_string($_POST['queryString']);
  // Is the string length greater than 0?
  if(strlen($queryString) >0) 
  {
    $query = $db->query("SELECT naam_klant FROM overboekingen WHERE naam_klant LIKE '$queryString%' LIMIT 10");     

    if($query)
    {
      while ($result = $query ->fetch_object())
      {
        echo '<li onClick="fill(\''.$result->naam_klant.'\');">'.$result->naam_klant.'</li>';
      }
    }
    else 
    {
      echo 'ERROR: There was a problem with the query.';
    }
  } 
  else 
  {
  } // There is a queryString.
} 
else 
{
  echo 'There should be no direct access to this naam_klant script!';
}   
}

There are a couple of mistakes in your fill function, try:

function fill(thisValue) 
{
  $('#naam_klant').val(thisValue);
  setTimeout("$('#suggestions').hide();", 200);        
}

You were looking for a text field with a class of "inputString" which doesn't exist. Likewise you were looking for a "suggestions" class, whereas "suggestions" is actually the div's ID. You may wish to change the suggestions div to a <ul> since you are loading <li>'s into it.

Here's a JSFiddle - http://jsfiddle.net/DjuJ4/1/ (note: I have replaced your ajax call with a static data variable for the purposes of testing)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM