Dynamic Type Ahead

Some people want the computer to read their minds. With a bit of Ajax and DHTML, we designers can make it appear as if the computer is doing just that, to a limited extent. Given a good database, as soon as visitors start typing information into a form field, the computer can begin to predict what they are looking for, and narrow it down further the more information they enter.

In this example (Figure 22.9), I'm using the common example of a form field used to submit a city name that a Web site visitor might be traveling to.

In cases in which visitors may not know the exact spelling of the city's name, a type ahead input field can help by displaying a list of potential names based on the letters the visitor has typed into the form field (Figure 22.10). The more of the name that is entered, the more the possibilities narrow and the options drop out (Figure 22.11), until the visitor clicks the correct city name(Figure 22.12). In addition, depending on how the database is set up, visitors can search based on airport codes or other criteria, such as a state abbreviation (Figure 22.13).

Figure 22.9. The form field, waiting for a city name to be entered.

Figure 22.10. As the visitor types, the browser displays possible matches underneath.

Figure 22.11. The possibilities become more specific as the visitor types in more letters.

Figure 22.12. At any time, the visitor can click one of the options to have the form field populated automatically.

Figure 22.13. The type-ahead input field can be based on a variety of criteria. For example, visitors can type in a state abbreviation to see all the cities in the same state.

To add a dynamic type-ahead input field:



Open a new external JavaScript file and save it as typeAhead.js (Code 22.12). Steps 2 through 5 apply to this file.

Code 22.12. typeAhead.js: Functions used for predicting what the visitor is typing using Ajax.

[View full width]

function typeAhead(objectPlace) {         requestedData = objectPlace.value;         fetchData('dataPage.php', requestedData,'results'); } function setCity(cityNameVal) {         document.forms.myForm.cityName.value = cityNameVal; } function filterData(pageRequest,objectID){ var objectResults = document.getElementById(objectID); if(pageRequest.responseText != '')         {         objectResults.style.display = 'block';         objectResults.innerHTML = '';         resultsList = pageRequest.responseText.split(',');         for(i = 0; i < resultsList.length; i++)         { if(resultsList[i] != "")         objectResults.innerHTML += '<a href="javascript:setCity(\'' + resultsList[i] + '\ ')" onclick="popHide(\'' + objectID + '\')">' + resultsList[i] + '</a>';                 } } else {         objectResults.style.display = 'none';         }} function popHide(objectID) {         var objPopUp = document.getElementById(objectID);         objPopUp.style.display = 'none';}


function typeAhead(objectPlace) {…}

Add the function typeAhead() to your JavaScript.

This function uses the ID for the input field to grab its current value (requestedValue). The function then passes that data and the name of the popup layer used to display the results ('results'), as well as the URL for the file on the server used to process the data (dataPage.php) to the Ajax basic function fetchData().


function setCity(cityNameVal) {…}

Add the function setCity() to your JavaScript. This function will take a value passed to it in the cityNameVal variable and place that into the cityName form input field.


function filterData(pageRequest, objectID){…}

Add the function filterData() to your JavaScript, which will replace the default version of the function included in the ajaxBasics.js file you will be linking to in Step 9.

This function takes the comma delimited list of city names delivered dynamically from dataPage.php, splits it up and turns each name into a link that calls the setCity() function, passing it the name of the city. It displays this list of links in the object specified by the variable objectID


function popHide(objectID) {…}

Add the function popHide() to your JavaScript. This function simply hides the layer in which the type-ahead list is being displayed.



Set up a page on your server that holds and processes the data you will be placing in your HTML page (Code 22.13).

Code 22.13. dataPage.php: A server page using PHP to store arrays of city names and possible matches.

<?php $cityName = array(); $cityResults = ""; $lastQuery = ""; $cityName["Charleston&sbquo; SC (CHS)"] = array("Charleston", "SC", "CHS"); $cityName["Charleston&sbquo; WV (CRW)"] = array("Charleston", "WV", "CRW"); $cityName["Charlotte&sbquo; NC (CLT)"] = array("Charlotte", "NC", "CLT"); $cityName["Charlottesville&sbquo; VA (CHO)"] = array("Charlottesville", "VA", "CHO"); $cityName["Greensboro&sbquo; NC (GSO)"] = array("Greensboro", "NC", "GSO"); if(isset($_POST["dataRequest"])) { $searchString = strtolower($_POST["dataRequest"]); $searchStringLength = strlen($searchString);                 foreach($cityName as $query=>$keywords)                 { foreach($keywords as $word)                     { $subString = substr($word,0,$searchStringLength);                        if (strtolower($subString) == $searchString) {                             if ($query != $lastQuery) {         $cityResults .= sprintf("%s,",$query);         $lastQuery = $query; }}}}            echo $cityResults; } ?>

In this example, I'm using a PHP file to create an array ($cityName[]) that records a city name and state as the index and then a list of corresponding strings that are associated with the city (city name, state, and airport code).

The script takes the value passed to it through the dataRequest variable in the XMLHttpRequest call and compares that string to each element in the array. If there is a match (even partial), it records that city and then sends the list of matching cities back to the calling page.



Create an external style sheet that holds your styles for this page and save it as typeAhead.css (Code 22.14). I used styles similar to those I set up in "Styling Forms" in Chapter 21. Make sure to define a class for .popUp {…} and set it to display: none.

Code 22.14. typeAhead.css: Add styles for your forms and type ahead fields, but always include the .popUp class.

.popUp {     position: relative;     font-size: .9em;     font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;     background-color: #fff;     display: none;     left: 148px;     padding: 8px;     width: 200px;     opacity: .8;     border: 1px solid black; }



Set up an HTML file and save it as index.html (Code 22.15). Steps 9 through 13 apply to this file.

Code 22.15. index.html: The Web page with a text form field for the visitor and a hidden layer that will eventually display possible matches.

[View full width]

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/ xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" ="text/html; charset=utf-8" /> <title>CSS, DHTML &amp; Ajax | Providing Dynamic Type Ahead</title> <script src="/books/3/292/1/html/2/ajaxBasics.js" type="text/javascript"></script> <script src="/books/3/292/1/html/2/typeAhead.js" type="text/javascript"></script> <link href="typeAhead.css" rel="stylesheet" type="text/css" /> </head> <body> <form action="#" method="get" >       <fieldset>       <legend>Personal Information</legend>       <label for="cityName">City</label>       <input type="text"   onkeyup="typeAhead(document. getElementById(this.id));" value="" />       <div  >&nbsp;</div>       <input  type="submit" name="submitButtonName"   value="Send" tabindex="9" /> </fieldset></form> </body></html>



Add a call to the ajaxBasics.js file created in Chapter 20 (Code 22.6). You will need to add a copy of this file to the directory or change the src value to the path where your Ajax basics (ajaxBasic.js) file is located.



Add a call to the typeAhead.js file you set up in Step 1.



Add a link to the typeAhead.css file you set up in Step 7.


[View full width]

<input type="text" class= "formInputText" onkeyup="typeAhead(document. getElementById(this.id));" value="" />

In the form on your page, add an <input> element with an ID value of cityName and an onkeyup event handler that triggers the function typeAhead() from Step 2. Pass the function element's ID (this.id).


<div  >&nbsp;</div>

Add a layer that will be used to display the type-ahead list as it is generated. Initially it should be hidden.

CSS, DHTML and Ajax. Visual QuickStart Guide
CSS, DHTML, and Ajax, Fourth Edition
ISBN: 032144325X
EAN: 2147483647
Year: 2006
Pages: 230

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net