Topic: Autocomplete form field

is there an example of autocomplete of a form field based on data stored on a table?

Thank you in advance.


Re: Autocomplete form field

Hi luigi,

I don't use xajax for my autocomplete needs but a jquery plugin available here:

It's really easy to use and can access backend php or an array in the html page.

Code for the head tag of the page:

<link rel='stylesheet' href='styles/jquery.autocomplete.css'>
<script src="//"></script>
<script language="javascript" src="scripts/jquery.autocomplete.js"></script>

I assign autocomplete in the js ready function:

    var autoparams = {width:260, autoFill: true, matchContains: true, selectFirst: false};
    //Autosuggest routines
    jQuery("#name").autocomplete("includes/auto_driver_names.php", autoparams);

The php for this access the database and selects like names from my dirvers (truck drivers) page and echos them back to the html page. It looks like this:

  $office = $_SESSION['officeid'];
      die("Could not connect to database");
  $q = strtolower($_GET["q"]);
  if ($q == '') return;
  $sql = "select id,name from drivers where name LIKE '%$q%' and officeid like $office";
  $rsd = mysql_query($sql);
  while($rs = mysql_fetch_array($rsd)) {
      $cname = $rs['name'];
    $id = $rs['id'];
    if ($cname !== '' && substr($cname,0,1) != '(')
      echo "$cname\n";

As the user types the atocomplete is invoked and a list of prospective matches appears below the autocomplete input field. The users select the one they want and it populated the input.

You could do it with xajax but why reinvent the wheel, to coin a cliche?


If you ever stop learning you may as well dig a hole, crawl in and pull the top over yourself.

Re: Autocomplete form field

Thank you for your answer.

I solved it with xajax because I needed a more deep interaction with the existing code.

I assigned an xajax function to onkeypress, onpaste and oninput. If the length of the input data is >4, a search on database is performed and a list is populated inside a <span>. In my case the list is limited to 10 items.

The list consists of a series of <a href='#'> with an onclick xajax function called with the ID of the selected item. This functions populates the fields, sets some variables needed for later processing and empties the <span>.