Hack 65. Create an Auto-Complete Field with script.aculo.us


Implement your own auto-complete field using script.aculo.us effects.

An increasingly common control for Ajax applications is a text field that "senses" the user typing. When the user types one or more letters, the application immediately checks the field value with a cached or server database. If there are any matches, these are displayed in a drop-down box beneath the text field. This behavior is usually referred to as auto-completion.

This hack requests the user to start typing in an email address. The typed characters are compared behind the scenes to a server-side data store, and if any matches are found, a drop-down box populated with those values appears (as in Google's Gmail). Figure 8-4 shows this effect, which is simple to implement using script.aculo.us.

Figure 8-4. Your own version of Gmail


script.aculo.us uses the Ajax.Request object of the Prototype library. See "Integrate script.aculo.us Visual Effects with an Ajax Application" [Hack #63] for a description of Prototype and this object.


When the user selects one of these displayed email addresses, it becomes the value of the text field.

To implement this hack, the developer must import the prototype.js and scriptaculous.js libraries, as in the following web page code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"        "http://www.w3.org/TR/2000/REC-xhtml1-20000126/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head>     <meta http-equiv="content-type" content="text/html; charset=utf-8" />     <script src="/books/4/254/1/html/2//javascripts/prototype.js" type="text/javascript"></script>     <script src="/books/4/254/1/html/2//javascripts/scriptaculous.js" type="text/javascript"></script>     <script src="/books/4/254/1/html/2//javascripts/auto_com.js" type="text/javascript"></script>     <style type="text/css">         @import "http://localhost:8080/stylesheets/hacks.css";     </style>     <title>auto-complete field</title> </head> <body> <h3>Enter Your Email Contact Name</h3> <div><form action="javascript:void%200"> <input type="text"  size="25" /> <div  style=         "background-color: #9EB5F2; font-size: 0.8em; border: solid thin;"> p</div> </form></div> </body> </html>

The imported auto_com.js file contains this hack's custom code, which uses a script.aculo.us object to implement the fancy control. Here is the code for that file:

window.onload=function(  ){      new Ajax.Autocompleter("ac", "ac_choices",             "/hacks/a_complete", {paramName: "chars", minChars: 2}); }

This code creates an Ajax.Autocompleter object when the browser finishes loading the web page. Ajax.Autocompleter is a built-in script.aculo.us object defined in controls.js. (Recall from "Integrate script.aculo.us Visual Effects with an Ajax Application" [Hack #63] that as long as your web page imports the JavaScript library scriptaculous.js, it loads its various dependencies, such as effects.js and controls.js, itself.

The Ajax.Autocompleter parameters are:

  • The id of the text field that implements auto-completion (this can also be implemented as a textarea; see the upcoming API information)

  • The id of the div element, for instance, that will contain the drop-down list of matching text

  • The URL of the server component that receives this control's Ajax request

  • A set of optional parameters in JavaScript object literal format

The code's parameters specify that the name of the variable containing what the user has typed so far is chars. An Ajax request is sent when the user has typed a minimum of two characters. In other words, once the user has typed two characters in the text field, the auto-completer sends those characters to the server component in a request parameter named chars.

There are several other parameters that developers can use with the Ajax.Autocompleter object. For details, see the API description at http://wiki.script.aculo.us/scriptaculous/show/Ajax.Autocompleter.


On the Server Side

The server component has to check the value of the sent parameter and then send the auto-completer some data in the response. The response has to be in the format of an HTML unordered list. First, here is the server-side code that receives the request at the URI /hacks/a_complete. This component or action is implemented with Ruby on Rails (discussed in Chapter 7):

def a_complete     #This data typically derives from a database     #Call a method returning an array of email contacts     #associated with a particular user     @emails = ["boston@city.com","bruceperg@yahoo.com",
"brucew@parkerriver.com", "bradpitt@comcast.net","brycegill@google.com", "billythorton@ycomcast.net", "bruceperry@comcast.net", "christophe@comcast.net"] #The chars request parameter holds the #characters that the user has typed in so far chars = params[:chars].to_s #Regular expression matching a string beginning with #the characters the user typed in, followed by #zero or more characters re = /^#{chars}.*$/ @mtch = [] for email in @emails if re.match(email) != nil @mtch.push(email) end end @mtch = @mtch.sort #Pass the array of matched emails on to the template render :partial => "auto_ul" end

The comments (preceded by #) describe what's going on in the Ruby method a_complete( ). We skipped the step of pulling dozens of email addresses out of a database for a user, and began with an array of email addresses that would be the typical return value of the database interaction. The code uses a regular expression to match the beginning of each email address with the characters that the user has entered. The code then stores the matching addresses in an array, and passes this array to a template that forms the basis of the server's return value.

The render :partial => "auto_ul" part is the RoR method that processes the template with the matched email addresses. (Recall that in Rails parlance, the template file is called a partial.) Here is what it looks like:

<ul > <% @mtch.each do |_word| %> <li ><%=_word%></li> <% end %> </ul>

The @mtch variable contains all the matched addresses. This Ruby code is designed to build and return an unordered list, which the Ajax.AutoCompleter object expects as a return value. This value is a ul tag with nested li tags, each specifying an email address. The drop-down that appears when the user types is styled in a way that removes the bullets from the ul/li tags (list-style-type: none) and highlights the selected email address in white against a blue background:

<!--div holding the drop-down filled with email addresses --> <div  style=         "background-color: #9EB5F2; font-size: 0.8em; border: solid thin;">

Here are the relevant rules in the hacks.css stylesheet that determines the display of the drop-down box:

ul.people li.selected { background-color: #ffffff; } li.person { list-style-type: none; }

"Create an Auto-Complete Field" [Hack #78] discusses an alternate usage and implementation of auto-complete fields.





Ajax Hacks
Ajax Hacks: Tips & Tools for Creating Responsive Web Sites
ISBN: 0596101694
EAN: 2147483647
Year: 2006
Pages: 138

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