Auto-suggestion textbox control for your webpage

Bruce SmithSoftware Engineer II
An auto-suggestion control saves your users some typing.  It's a sort of combo-box that keys on the user input to automatically present a list of matching options.  You've seen the functionaity on the Google main page:  As you type, it displays a drop-down box that lists a set of suggestions.  You can then click an item to have it auto-complete the input.

Google's auto-suggestion box is very sophisticated, and I mention it only to give you the general idea.  Today's simple example is much less ambitious.  We'll discuss how to set up a text input box that is paired with a hidden listbox that's pre-filled with "suggestions" that have been read from from a server-side database.   Then we'll look at some code to handle the U/I events --- and save your users some effort.

To follow along you'll need a PHP web-page and a database such as MySQL to obtain the list of values.

1. Create a new PHP web-page and insert a text-field that has a default size of 25%

2. Create a div with a width of 25% and set the visibility attribute to 'hidden' and a relatively short
    height like around 100-150px and set the id attribute to something relevant like 'divSuggestions'
    because we'll be referring to this div quite often via JavaScript's getElementById() function.
That's it!  We'll use a little JavaScript to toggle the visibility of the box and some PHP and JavaScript combined to fill the box with relevant values from our database.

Somewhere in the header section we need to create a JavaScript array variable that we'll use a little later.  I'm calling this variable 'nameArray' because I'm looking up first and last names for my list of values.
<script type="text/javascript">
                          var nameArray = null;

Open in new window

Okay, we now have the HTML essentials as far as the text and suggestion-list boxes are concerned. Now we need to add functionality to these elements. When the user begins typing, we want the suggestions box to display and the user's input to show in the text-box.  For instance, when a user types in the letter 's', we want the suggestions box to show all values from our table that begin with the letter 's'.
scrnShot for input s
There are a lot of little things that we need to take into consideration when it comes to functionality. For this super-simple example we're going to display the box whenever a user begins to type. If the user types input to the point where there are not any matching values, the box disappears. The box will also disappear when the user erases all the text in the box (i.e. the text-box is empty).

We will want to 'highlight' the suggestions when the user moves the mouse over them and add an event when the user clicks on a suggestion, the suggestions box disappears and the textbox is filled with the selected suggestion.

Finally we will make the suggestions box disappear when the user clicks anywhere in the page outside of the suggestions box. All these little features makes for a nice, simple suggestions-box familiar to anyone wh's used the Google search box.

Let's get to JavaScript-ing and PHP-ing!  Down at the bottom of the page just inside the </body> tag we'll create our javascript section. Inside the javascript tags we'll need to create 4 functions.

We need to create a function that grabs the input text as the user types and determine if the suggestions box should show or not. Remember: 'divSuggestions' is the id of my textbox.

function doSuggestionBox(text) { // function that takes the text box's inputted text as an argument
                          var input = text; // store inputed text as a variable for later manipulation
                          // determine whether to display suggestion box or not
                          if (input == "") { // hide the suggestion box
                              document.getElementById('divSuggestions').style.visibility = 'hidden';     
                          } else {  // show the suggestion box
                              document.getElementById('divSuggestions').style.visibility = 'visible'; 

Open in new window

When a user clicks on a suggestion, we want to hide the suggestion box and display the selected suggestion in the text box (the ID of my text box is 'txtSearch').

function doSelection(text) { // function that grabs the selected suggestion and hides the suggestions box and places the selected suggestion in the text box
                          var selection = text;
                          document.getElementById('divSuggestions').style.visibility = 'hidden'; // hides the suggestion box
                          document.getElementById("txtSearch").value = selection; // sets the text in the textbox to the selected suggestion

Open in new window

When a user moves the mouse over a suggestion, we want to highlight it. You can use whatever colors you want - I'm using (background/foreground) purple/white and white/black.
scrnShot for highlight
function changeBG(obj) { // when the mouse hovers over a suggestion, the suggestion is highlighted
                          element = document.getElementById(obj);
                          oldColor =;
                          if (oldColor == "purple" || oldColor == "") {
                     = "white";
                     = "purple";
                     = "pointer";
                          } else {
                     = "purple";
                     = "white";
                     = "default";

Open in new window

The following function actually creates the suggestions as individual divs to place into the suggestions box.
function doSuggestions(text) { // actually displays the relevant suggestions in the suggestions box
                          var input = text;
                          var inputLength = input.toString().length;
                          var code = "";
                          var counter = 0;
                          // loop through our array of values to determine which ones are matching suggestions
                          while( counter < this.nameArray.length) { 
                              var x = this.nameArray[counter]; // avoids retyping this code a bunch of times
                              // if statement that determines if the inputed text matches the value from our list of
                              //  values - if true, adds the suggestion to the list
                              if(x.substr(0, inputLength).toLowerCase() == input.toLowerCase()) { 
                                   // The relative suggestion is a div that we'll place into the suggestions box. You can see
                                   //  how we're implementing a couple of the previous functions we created previously.
                                  code += "<div id='" + x + "'onmouseover='changeBG(;' onMouseOut='changeBG(;' onclick='doSelection(this.innerHTML)'>" + x + "</div>";
                              counter += 1;
                          if (code == "") {
                          document.getElementById('divSuggestions').innerHTML = code; // adds the suggestions to the suggestions box
                          document.getElementById('divSuggestions').style.overflow='auto'; // shows a vertical scroll bar if needed

Open in new window

Okay, we're almost done. All we need to do now is grab the list of values from our database. So at the top of our page just inside the <body> tag we'll add our <?php ?> section. Inside our php section we need to connect to the database and store the list of values in the JavaScript array that we created at the beginning. I called mine 'nameArray' because I'll be getting first and last names from my database.
mysql_connect("your database server", "username", "password") OR DIE ('Unable to connect to database! Please try again later.');
                      mysql_select_db('your database name');
                      $query = 'SELECT user_lname, user_fname FROM user ORDER BY user_lname ASC';
                          $result = mysql_query($query);
                          $counter = 0;
                          // write the values from the database into the javascript array
                              echo("<script type='text/javascript'>");
                              echo("this.styleListArray = new Array();");
                              if ($result) {
                                  while($row = mysql_fetch_array($result)) {
                                      echo("this.nameArray[" . $counter . "] = '" . $row['user_lname'] . ", " . $row['user_fname'] . "';"); // displays 'lname, fname'
                                      $counter += 1;

Open in new window

And the last thing that we need is to set the onclick event for the body so that when the user clicks anywhere on the page outside of the suggestions box, the suggestions box will hide. And when the user types in the box we need to call the doSuggestionBox function - so we need to set the onkeyup event for the text box.
<body onclick="document.getElementById('divSuggestions').style.visibility='hidden'">

Open in new window

That's it. Now you have a working Google-like suggestions box. My source code is attached. Of course you can add more features and functionality as seen fit.

Bruce SmithSoftware Engineer II

Comments (4)

Fahad PathanTeam Leader

This is about PHP, what about Asp.Net?
Bruce SmithSoftware Engineer II


@pathan_fahad: Very similar seeing that you'll use the same javascript features. I'll do a sample page for you in Asp .NET tomorrow.

Bruce SmithSoftware Engineer II


A working example can be found here:
Vimal DMSenior Software Engineer


There is best example here: "".

Using jquery can make this possible.

Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.