Over the years I’ve experimented with several autocomplete scripts, some were really nice to implement, others were really weak sauce. Recently, I had to once again implement an autocompete field in an input form, and decided it was time to take another look at my favorite library, jQuery, to get this done.

Well, in this instance I’m happy to report I had great success using a basic implementation of the jQuery Autocomplete Plugin. And for that, I decided to share my solution. The demo is here.

Requirements Overview

My requirements were that I needed to have a single autocomplete field, “keywords”, in an input form. The keywords would be derived from a column in a MySQL table called “tblKeywords”. My scripting language is PHP. There is no restriction on the actual field regarding the input of a new keyword, basically the autocomplete is just a friendly suggestion.

Start by including the jQuery library and CSS files in the header, the following 3 things are required:

<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/themes/base/jquery-ui.css" type="text/css" media="all" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/jquery-ui.min.js" type="text/javascript"></script>

The HTML

Just a simple form, I’m only going to use a single field for this tutorial, obviously there can be a bunch of other fields based on your needs.

<form action="process-me.php" method="post">
  <label>Keyword:</label>
  <input id="keywords" name="keywords" type="text" value="" />
</form>

The PHP

We need to create a database query to get all the keywords, and then output them to a javascript variable, specifically, an array. Of course this can all be done via an ajax call, but like I said, this is a simple way to do it and it works, so why mess with it? We’ll create a function to do our work for us.

function keywordArray()
{
  global $connectionString;
  $keywordsSQL = "SELECT * FROM tblKeywords";
  $rsKeywords = mysql_query($keywordsSQL, $connectionString);

  $output = '<script>'."\n";
  $output .= 'var keywordList = [';

  while($row_rsKeywords = mysql_fetch_assoc($rsKeywords))
  {
    $output .= '"'.$row_rsKeywords['name'].'",';
  }

  $output = substr($output,0,-1); //Get rid of the trailing comma
  $output .= '];'."\n";
  $output .= '</script>';
  return $output;
}

The Javascript

With the javascript we want to do 2 things right before the closing </head> tag:

1. Call the  jQuery function in reference to the input field (by ID) and the array that holds the variables:

$(document).ready(function() {
  $("#keywords").autocomplete({
    source: keywordList
  });
});

2. Print the javascript array with the variables:

<?php echo keywordArray(); ?>

And that’s it! Pretty straightforward, and super quick to implement.