<

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x

Auto-suggestion textbox control for your webpage

Published on
19,302 Points
13,102 Views
2 Endorsements
Last Modified:
Approved
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;
</script>

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'; 
        doSuggestions(text);
    }
}

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 = element.style.backgroundColor;
    if (oldColor == "purple" || oldColor == "") {
        element.style.background = "white";
        element.style.color = "purple";
        element.style.cursor = "pointer";
    } else {
        element.style.background = "purple";
        element.style.color = "white";
        element.style.cursor = "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(this.id);' onMouseOut='changeBG(this.id);' onclick='doSelection(this.innerHTML)'>" + x + "</div>";
        }
        counter += 1;
    }
    if (code == "") {
        document.getElementById('divSuggestions').style.visibility='hidden';
    }
    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;
            }
        }
    echo("</script>");

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'">
onkeyup="doSuggestionBox(this.value);"

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.

-cheers
suggestion-box.php
2
Comment
Author:Bruce Smith
  • 2
4 Comments
LVL 2

Expert Comment

by:Fahad Pathan
This is about PHP, what about Asp.Net?
0
LVL 11

Author Comment

by:Bruce Smith
@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.

-Cheers
0
LVL 11

Author Comment

by:Bruce Smith
A working example can be found here: http://patsmitty.com/suggestion_box.php
0
LVL 7

Expert Comment

by:Vimal DM
Hey,

There is best example here: "http://jqueryui.com/autocomplete/".

Using jquery can make this possible.
0

Featured Post

CompTIA Security+

Learn the essential functions of CompTIA Security+, which establishes the core knowledge required of any cybersecurity role and leads professionals into intermediate-level cybersecurity jobs.

Join & Write a Comment

Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month