The jQuery community has a vast array of plug-ins freely available for use – you can see them at the jQuery plug-ins site. There are also existing UI widgets available from the jQuery-UI project.
In this tutorial, we're going to take a jQuery-UI widget and show you how to implement it – the autocomplete widget.
What's an Autocomplete?
The autocomplete is a widget which attaches to and adds functionality for a standard HTML text field; it provides suggestions while you type into the field.
The autocomplete gets its list of suggestions from a javascript array, and you can provide that javascript array from one of three locations:
- Embedded in the HTML page
- A URL which returns data in JSON format
- A callback function
01: Setting up your HTML page
In order to make use of this widget, you're going to need three library files included in your page. Luckily you can use the free Google CDN for all three files.
- The jQuery-UI CSS file
- The jQuery Library
- The jQuery-UI Library
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/black-tie/jquery-ui.css" type="text/css" /> <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'></script> <script src='http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/jquery-ui.min.js'></script>
<form> <input id="AC" type="text" /> </form>
02: The Most Basic Autocomplete
Back up in the head of the document, we're going to put script tags after all the included files, and then wrap the call to the plug-in in a document.ready block. After the ready block, we'll include the array 'programmingLang'.
<script> /* Example #1 - Programming Languages */ $(document).ready(function() { $( "#AC" ).autocomplete({ source: programmingLang }); }); var programmingLang = ["ActionScript","AppleScript","Asp","BASIC","C","C++", "Clojure","COBOL","ColdFusion","Erlang","Fortran","Groovy","Haskell", "Java","JavaScript","Lisp","Perl","PHP","Python","Ruby","Scala","Scheme"]; </script>
03: JSON from the Server Autocomplete
This option is more powerful, but you have to write the matching code yourself. Everything the server returns in JSON format is shown as an option, so if you return "Illinois" when someone types in "ZZ" that's what the widget thinks will match. Here's the set-up for using a remote data source:
$(document).ready(function() { $( "#STATES" ).autocomplete({ source: "states.php", }); });
$STATES = array('AL'=>"Alabama",
'AK'=>"Alaska",
# etc for all 50 states
);
$term = $_GET['term'];
if(strlen($term) == 2) {
$UC = strtoupper($term);
if(isset($STATES[$UC])) { $return[] = $STATES[$UC]; }
}
foreach($STATES as $k=>$v) {
if(preg_match("/^$term/i", $v)) { $return[] = $v; }
}
foreach($STATES as $k => $v) {
if(preg_match("/$term/i", $v)) { $return[] = $v; }
}
echo json_encode(array_values(array_unique($return)));
If you use this method, the data source must be on the same domain as the requesting page.
04: Function as Autocomplete
The third option to supply your autocomplete with data is a function. Using a function is more powerful then the other two options; you can use it to return custom sorted data from an in page array, or to fetch and aggregate data from multiple scripts. You can even use it to fetch data from a URL not on the same server (JSONP).
In order to get data from a server other then the one the page is hosted on, you must use JSON-P (which stands for JSON-Padded). Basically the server must know to return the data wrapped in a function call which is then executed by the browser. jQuery has JSON-P handling built right in.
$( "#REMOTE" ).autocomplete({ source: function( request, response ) { url = "http://www.medetis.com/give-up-already/autocomplete/remote.php?term=" + request.term; $.getJSON(url + '&callback=?', function(data) { response(data); }); } });
- request: Has the string from the text box stored in request.term
- response: Is a function reference which expects to have the data to show passed to it
In the callback of $.getJSON, we then pass the received data to the 'response' function reference. You can do any other processing of the variable data that you want to previous to this point.
This example will work even if you run the example.html file from your desktop. The second example won't because it can't request data from a source not on the same domain.
The server side code for JSON-P also changes a little bit -- only one line. When returning data to the browser, it's going to be formatted as a function wrapping a JSON string. The value of 'callback' has been provided by jQuery. So the last line of the server side script would be:
echo $_GET['callback'] . '(' . json_encode(array_values(array_unique($return))) . ');';
Source code: auto-complete.zip
Conclusion
jQuery has many great prebuilt plug-ins you can use in your applications and websites today. Both the jQuery-UI project, and the main jQuery plug-ins site are great resources you should take advantage of in your jQuery development.
Message