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.
<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.
$(function() {
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.
$("#presidentsClientInput").autocomplete( { source: presidents });
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.
<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" />
<br />
<label for="presidentsServerInput">Select President (server-side): </label>
<input id="presidentsServerInput" />
</body>
</html>
$("#presidentsClientInput").autocomplete( { source: presidents });
$("#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.
<?php
$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.
function filter($president) {
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.
Source Files:
great and very useful post. I was looking to implement this. thanks.
very useful!! tks
zip/rar code to download?
It's right at the bottom of the post, under the section called "Source Files".
ups!..sorry and tks!!
How can i add html anchor tag with the displayed results in case of presidents from server side?.I wanted to display the search results like we have in facebook,and when you click on the search results it opens up the user profile.
Thanks in advance.
In this tutorial, I used the most basic data format accepted by the autocomplete widget - an array of strings. The widget will also accept an array of objects with two properties - label and value. The label will be what's displayed and the value is what's entered into the form field if you're using forms.
To do what you want, have the PHP create an array of objects that have the label and value properties. The value property should be the URL of the site you'd like to go to. In jQuery, bind to the autocomplete widget's change event and navigate to the URL when the event occurs.
Hi Reddest,thanks for replying. I might sound very dumb here but i am not able to figure out how to make my array of string i.e names into an array of objects having label and value. Secondly,in the form when i get the list of names in the text field.Which event should i use to capture the name and not the text entered by the user?
PHP the code that i am trying to use.
Well, first you need to declare an object.
Then create and populate these in your MySql block.
Then change the filter method to look at the label property.
This should get you started on the right track. I didn't test any of this, so there may be small tweaks needed.
Based on the documentation, it looks like the change event is what you'll want to hook.
I'm getting so close here. Is there a change to the "print(json_encode(array_values . . . " statement? My page looks like it is trying to display something, but it will not complete properly.
Thanks for this, it is very useful.
Just getting started with jQuery. Do I need to download both jQueryUI and the regular jQuery to use this autocomplete feature?
I found out that downloading a jQuery UI package includes a jQuery package.
Thanks anyway.
thanks
Hi Brandon Cannaday, I am new to php. I want to know how can i fetch the id and the value both in the json for autocomplete textbox. and i want to store the id in the hidden field