Autocomplete on input fields in forms has become more and more popular, especially following Google's implementation of it in 2009. Between 2008 and 2010, numerous autocomplete plugins for jQuery popped up, which enabled developers to easily install the enhancement.
With the release of version 1.8.3 of the jQuery UI Library, the autocomplete function became part of the core files, making it even easier to implement on websites and web applications.
So, here is how it is done.
To preserve graceful degredation, autocomplete is invoked by applying a specific class to the input field. For example:
<label for="county">County</label>
<input type="text" name="county" id="county" title="enter a county" class="autocomplete" />
This example uses JSON to query a PHP file, which pulls results from a database. If you wanted the jQuery to look at a static list of options instead of using a callback function, you would need to modify the source attribute accordingly.
$("input.autocomplete").autocomplete({
//source: ["c++", "java", "php", "coldfusion", "javascript", "asp"]
minLength: 2,
source: function(request, response) {
$.getJSON('path to PHP file', request, function(data) {
var suggestions = [];
$.each(data, function(i, val) {
suggestions.push(val.name);
});
response(suggestions);
});
}
});
The autocomplete function will send the value of the text input inside the $_GET['term'] variable. You can then use this variable to query the database to find matches.
jQuery expects the response to be a JSON encoded array, so when returning your results to the javascript, make sure that you run the json_encode PHP function and send a Content-type: text/x-json header.
The json_encode function was only included in releases of PHP 5.2.0 onwards, so if you are running a lesser version, you will need to download and include JSON's encode and decode functions, available here.
Try it out for yourself. This autocomplete example suggests counties in the UK and Ireland.