spacer

Webref WebRef   Sitemap · Experts · Tools · Services · Newsletters · About i.com

home / programming / javascript / ncz / column2 / 1 To page 1To page 2To page 3current page
[previous]

Web Project Manager
Aquent
US-PA-Collegeville

Justtechjobs.com Post A Job | Post A Resume
Developer News
Mandrake Linux Founder Back, Virtually
Amazon: We're a Technology Company
Sun Expands MySQL With Closed Source

Creating an Autosuggest Textbox with JavaScript, Part 2

To handle the up arrow, down arrow, and Enter keys, a handleKeyDown() method is necessary. Similar to handleKeyUp(), this method also requires the event object to be passed in. Once again, you'll need to rely on the key code to tell which key was pressed. The key codes for the up arrow, down arrow, and Enter keys are 38, 40, and 13, respectively. The handleKeyDown() method is defined as follows:

AutoSuggestControl.prototype.handleKeyDown = function (oEvent) {
    switch(oEvent.keyCode) {
        case 38: //up arrow
            this.previousSuggestion();
            break;
        case 40: //down arrow
            this.nextSuggestion();
            break;
        case 13: //enter
            this.hideSuggestions();
            break;
    }
};

Remember, when the user presses the up or down arrows, the suggestion is automatically placed into the textbox. This means that when the Enter key is pressed, you need only hide the dropdown list of suggestions.

Updating init()

Now that all of this new functionality has been added, it must be initialized. Previously, the init() method was used to set up the onkeyup event handler, now it must be extended to also set up the onkeydown and onblur event handlers, as well as create the dropdown suggestion list. The onkeydown event handler is set up in a similar manner as onkeyup:

AutoSuggestControl.prototype.init = function () {

     var oThis = this;

    this.textbox.onkeyup = function (oEvent) {
        if (!oEvent) {
            oEvent = window.event;
        }

        oThis.handleKeyUp(oEvent);
    };

    this.textbox.onkeydown = function (oEvent) {

        if (!oEvent) {
            oEvent = window.event;
        }

        oThis.handleKeyDown(oEvent);
    };


    //more code to come
};

As you can see, the same algorithm is used with the onkeydown event handler: first determine the location of the event object, then pass it into the handleKeyDown() method.

Up to this point, the only way the dropdown list is hidden is when the user hits the Enter key. But what if the user clicks elsewhere on the screen or uses the Tab key to switch to a new form field? To prepare for this, you must set up an onblur event handler that hides the suggestions whenever the textbox loses focus:

AutoSuggestControl.prototype.init = function () {

    var oThis = this;

    this.textbox.onkeyup = function (oEvent) {
        if (!oEvent) {
            oEvent = window.event;
        }

        oThis.handleKeyUp(oEvent);
    };

    this.textbox.onkeydown = function (oEvent) {

        if (!oEvent) {
            oEvent = window.event;
        }

        oThis.handleKeyDown(oEvent);
    };

    this.textbox.onblur = function () {
        oThis.hideSuggestions();
    };


    this.createDropDown();
};

You'll also notice that the createDropDown() method is called to create the initial dropdown list structure. With the initializations complete, it's time to test out your creation.

Example

The example for the updates is set up in the same way as Part 1. The only difference is in the code that is used and the inclusion of the style sheet:

<html>
    <head>
        <title>Autosuggest Example 2</title>
        <script type="text/javascript" src="autosuggest2.js"></script>
        <script type="text/javascript" src="suggestions2.js"></script>
        <link rel="stylesheet" type="text/css" src="autosuggest.css" />

        <script type="text/javascript">
            window.onload = function () {
                var oTextbox = new AutoSuggestControl(document.getElementById("txt1"), new StateSuggestions());
            }
        </script>
    </head>
    <body>
        <p><input type="text" id="txt1" /></p>
    </body>
</html>

As before, the autosuggest2.js file contains the AutoSuggestControl definition and suggestions2.js contains the StateSuggestions definition. The creation of the AutoSuggestControl is handled in exactly the same way.

You can view the example here (it should work in Internet Explorer 5.5+ and Mozilla 1.0+, including Firefox) or download it.

With the dropdown list and keyboard controls all working properly, there's only one part left to implement: going back to the server to get the suggestions. We'll examine this in the third and final part of this series.

About the Author

Nicholas C. Zakas is a user interface designer for Web applications and is the author of Professional JavaScript for Web Developers (Wiley Press, ISBN 0764579088). Nicholas can be contacted through his Web site, http://www.nczonline.net/, where he provides open source JavaScript libraries and tools.

home / programming / javascript / ncz / column2 / 1 To page 1To page 2To page 3current page
[previous]

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info

Legal Notices, Licensing, Reprints, Permissions, Privacy Policy.
Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Whitepapers and eBooks

Symantec Whitepaper: Converging System and Data Protection for Complete Disaster Recovery
Intel Whitepaper: Comparing Two- and Four-Socket Platforms for Server Virtualization
IBM Solutions Brief: Go Green With IBM System xTM And Intel
HP eBook: Simplifying SQL Server Management
IBM Contest: Are You the Next Superstar? Join the "Search for the XML Superstar" Contest to Find Out
Intel PDF: Quad-Core Impacts More Than the Data Center
Intel PDF: Virtualization Delivers Data Center Efficiency
Go Parallel Article: PDC 2008 in Review
Avaya Article: Communication-Enabled Mashups: Empowering Both Business Owners and IT
Intel Whitepaper: Building a Real-World Model to Assess Virtualization Platforms
PDF: Intel Centrino Duo Processor Technology with Intel Core2 Duo Processor
Microsoft Article: Build and Run Virtual Machines with Hyper-V Server 2008
  Go Parallel Article: Q&A with a TBB Junkie
IBM Whitepaper: Innovative Collaboration to Advance Your Business
Internet.com eBook: Real Life Rails
IBM eBook: The Pros and Cons of Outsourcing
Internet.com eBook: Best Practices for Developing a Web Site
IBM CXO Whitepaper: The 2008 Global CEO Study "The Enterprise of the Future"
Avaya Article: Call Control XML in Action - A CCXML Auto Attendant
IBM CXO Whitepaper: Unlocking the DNA of the Adaptable Workforce--The Global Human Capital Study 2008
Adobe Acrobat Connect Pro: Web Conferencing and eLearning Whitepapers
Symantec Whitepaper: Comprehensive Backup and Recovery of VMware Virtual Infrastructure
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
webref The latest from WebReference.com Browse >
Popular JavaScript Framework Libraries: An Overview - Part 3 · Accessing Your MySQL Database from the Web with PHP · Working with the DOM Stylesheets Collection
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Fixing MySQL Replication · Firewall Guide: First Steps to Securing the Enterprise · VoxOx Tames the Tumultuous Communications Tangle

Created: March 27, 2003
Revised: April 08, 2005

URL: http://webreference.com/programming/javascript/ncz/column2/1