With jQuery 1.8 came a brand new widget – the autocomplete input field. If used correctly, like in the case of Google’s search suggestions, autocomplete can provide a major boost in productivity. Today’s tutorial is going to demonstrate how to build and populate one of these autocomplete inputs. We’re going to make two identical examples that get their data from two different sources – one will be client-side and the other will be server-side using PHP.
The example dataset will include all of the presidents of the United States. As you begin typing, the input field will automatically popup with suggestions that match your query. Feel free to play with the example below. Some good examples would be “George Washington” or “Abraham Lincoln”.
Client Side
The first example we’ll build today will be entirely client-side. This is by far the easiest approach to take, but obviously the least powerful. The jQuery demo page for autocomplete has a very nice example that we’re basically going to replicate with different data. Let’s start with the html.
<link type="text/css" rel="stylesheet" media="all"
href="jquery-ui-1.8.9.custom.css" />
<script type="text/javascript" src="jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="jquery-ui-1.8.9.custom.min.js"></script>
<script type="text/javascript" src="presidents.js"></script>
<body>
<label for="presidentsClientInput">Select President (client-side): </label>
<input id="presidentsClientInput" />
</body>
</html>
Most of the code here is just getting jQuery included. The important part is the label and the input field. The input needs to have an id so we can reference it later and turn it into an autocomplete field.
Let’s jump into the javascript now – the source of presidents.js. The first thing we need is a datasource, which should be a simple array of values. jQuery does the work of iterating through these values to find the ones that match the text already in the input field.
var presidents = [
"George Washington",
"John Adams",
"Thomas Jefferson",
"James Madison",
"James Monroe",
"John Quincy Adams",
"Andrew Jackson",
"Martin Van Buren",
"William Henry Harrison",
"John Tyler",
"James Knox Polk",
"Zachary Taylor",
"Millard Fillmore",
"Franklin Pierce",
"James Buchanan",
"Abraham Lincoln",
"Andrew Johnson",
"Ulysses Simpson Grant",
"Rutherford Birchard Hayes",
"James Abram Garfield",
"Chester Alan Arthur",
"Grover Cleveland",
"Benjamin Harrison",
"Grover Cleveland",
"William McKinley",
"Theodore Roosevelt",
"William Howard Taft",
"Woodrow Wilson",
"Warren Gamaliel Harding",
"Calvin Coolidge",
"Herbert Clark Hoover",
"Franklin Delano Roosevelt",
"Harry S. Truman",
"Dwight David Eisenhower",
"John Fitzgerald Kennedy",
"Lyndon Baines Johnson",
"Richard Milhous Nixon",
"Gerald Rudolph Ford",
"James Earl Carter, Jr.",
"Ronald Wilson Reagan",
"George Herbert Walker Bush",
"William Jefferson Clinton",
"George Walker Bush",
"Barack Hussein Obama"
];
});
Once we’ve got a datasource, it’s time to tell jQuery to turn our input field into an autocomplete input field.
We get the element with the id of “presidentsClientInput” and use the autocomplete function to convert it into an autocomplete field. The source property, in this case, points to our array of presidents. That’s all there is to it, the client-side autocomplete input field is done.
Server Side
Instructing the autocomplete field to get its data from a server is a little more complicated, but still not too bad. The first thing we need to do is add the field to our HTML and javascript.
<link type="text/css" rel="stylesheet" media="all"
href="jquery-ui-1.8.9.custom.css" />
<script type="text/javascript" src="jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="jquery-ui-1.8.9.custom.min.js"></script>
<script type="text/javascript" src="presidents.js"></script>
<body>
<label for="presidentsClientInput">Select President (client-side): </label>
<input id="presidentsClientInput" />
<br />
<label for="presidentsServerInput">Select President (server-side): </label>
<input id="presidentsServerInput" />
</body>
</html>
$("#presidentsServerInput").autocomplete( { source: "presidents.php" });
All I did was add a new label and input with a different id. I then added another line to the presidents.js file to setup the new input as an autocomplete field. This time, instead of setting the source to a local array, I set it to a string, which means jQuery will use this as a callback URL. It will automatically append a GET argument called “term” with the value of what’s in the input field. So, in this case, my php file will be called as “presidents.php?term=George”.
Everything for the client is now complete. It’s time to move on to the PHP file. Just like with the javascript, the first thing we need is the datasource.
$searchTerm = $_GET[‘term’];
$presidents = array(
"George Washington",
"John Adams",
"Thomas Jefferson",
"James Madison",
"James Monroe",
"John Quincy Adams",
"Andrew Jackson",
"Martin Van Buren",
"William Henry Harrison",
"John Tyler",
"James Knox Polk",
"Zachary Taylor",
"Millard Fillmore",
"Franklin Pierce",
"James Buchanan",
"Abraham Lincoln",
"Andrew Johnson",
"Ulysses Simpson Grant",
"Rutherford Birchard Hayes",
"James Abram Garfield",
"Chester Alan Arthur",
"Grover Cleveland",
"Benjamin Harrison",
"Grover Cleveland",
"William McKinley",
"Theodore Roosevelt",
"William Howard Taft",
"Woodrow Wilson",
"Warren Gamaliel Harding",
"Calvin Coolidge",
"Herbert Clark Hoover",
"Franklin Delano Roosevelt",
"Harry S. Truman",
"Dwight David Eisenhower",
"John Fitzgerald Kennedy",
"Lyndon Baines Johnson",
"Richard Milhous Nixon",
"Gerald Rudolph Ford",
"James Earl Carter, Jr.",
"Ronald Wilson Reagan",
"George Herbert Walker Bush",
"William Jefferson Clinton",
"George Walker Bush",
"Barack Hussein Obama"
);
?>
I immediately get the search term out of the GET arguments and then declare an array of presidents. Most applications will probably use some sort of database, but for clarity and simplicity, I went with a basic array.
Next we need to search the array for names that contain the text entered by the user, json encode the results, and return it back to the client.
global $searchTerm;
return stripos($president, $searchTerm) !== false;
}
print(json_encode(array_values(array_filter($presidents, "filter"))));
I use PHP’s array_filter function to filter the array of presidents. This function takes a callback that will be invoked on each element. If the callback returns true, the item will be added to the filtered array. To decide whether or not an item should be added to the filtered array I used stripos, which looks for an occurrence of a string using a case-insensitive compare.
The array_filter function creates an array with keys that are the index in the original array. The autocomplete field does not know how to use an array like that, so I use array_values to strip out the keys. The last thing I do is encode the array as json and print it.
That’s all there is to it for a fully functional server-side autocomplete input field. Hopefully you can use this as a starting point for some much more complicated and interesting scenarios. I didn’t show it here, but the autocomplete widget supports a more powerful callback that essentially gives you full control over how the results are returned. No matter what your system looks like, jQuery’s autocomplete widget should be able to accommodate it.
That does it for this tutorial. If you’ve got any questions feel free to leave them below or check out the forums.