Topic: Autocomplete form field

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



Thank you in advance.


ciao,
luigi

Re: Autocomplete form field

Hi luigi,

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

https://github.com/agarzola/jQueryAutocompletePlugin

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="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script language="javascript" src="scripts/jquery.autocomplete.js"></script>

I assign autocomplete in the js ready function:

jQuery(document).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:

<?php
  include("search_commons.php");
  $office = $_SESSION['officeid'];
  include("../dbsettings.php");
  $con=mysql_connect($dbhost,$dbuser,$dbpassword);
  if($con){
      mysql_select_db($dbdatabase,$con);
  }
  else{
      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?

Ed

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>.



ciao,
luigi