JavaScript
  Home arrow JavaScript arrow Javascript AutoComplete
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
JAVASCRIPT

Javascript AutoComplete
By: Chris Root
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 3 stars3 stars3 stars3 stars3 stars / 31
    2005-06-08

    Table of Contents:

    Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Web designers must always keep usability in mind when designing web sites. A site must allow quick and easy access to information during the very short time that a site first holds a visitor's interest. Any confusion that ensues about where things are, and that person's business is gone. Providing a way to precisely search for what they need is an excellent way to provide that usability. What Chris Root explains in this article is a way for your visitors to find and select items contained in long lists. He will also suggest ways to expand this to searching within HTML or XML documents.

    Auto-Complete

    Many desktop applications have user interface controls that allow a user to find matches for things as they type. This feature can be very useful for long lists of items such as states, countries, streets or product categories. Many web browsers implement this sort of functionality in their address bars. As you type, web site address matches that are part of a list of recently visited sites appear in a menu below the address bar. This reduces the amount of time it takes to access information.

    Another place this is implemented is in HTML select menus. Unfortunately this only works with the first letter typed, it is not implemented in all browsers on all platforms and it doesn't shorten the list of choices to only matches.

    The script described in this article will allow a user to begin typing what they are looking for in a text box while a select menu updates itself with matches. In the example the list comes from the contents of the select menu but it can also come from other sources.

    The HTML

    The HTML for this project is pretty simple. You could however use this script several places in a large form with multiple lists of information with no trouble. This example uses a list of city streets.

    <body onLoad="fillit(sel,entry)">
    <div>Enter the first three letters of a street and select a match from the menu.</div>
    <form><label>
    Street
    <input type="text" name="Street" id="entry" onKeyUp="findIt(sel,this)"><br>
      <select id="sel">
            <option value="s0001">Adams</option>
            <option value="s0002">Alder</option>
            <option value="s0003">Banner</option>
            <option value="s0004">Birchtree</option>
            <option value="s0005">Brook</option>
            <option value="s0007">Cooper</option>
    <!--and so on and so forth-->
      </select></label>
    </form>
    </body>
    </html>

    When the text box registers a keyUp event, the find() function calls and passes two parameters, the id of the select menu and a reference to the text field.

    For something like state information, allow the user the choice of using the auto-complete script or just selecting something from the menu, especially if they know the item they wish to select is at the top of the list. If someone lives in Alabama for instance, there is no need to have them enter the first three letters of their state when the item they want is at the top of the list of states. Fill the select menu (a list box can be used as well) with all the values and text labels that you want your user to choose from in the HTML code to start with.

    Alternatively, depending on the information in the list, the choice may not be as obvious. In this case you could store it in an array only and the user would always need to select a match. If there was only one match, and that match was the correct one, they could leave the menu alone. Otherwise they would need to select from the available matches displayed in the menu.

    The longer the list the more useful our script becomes. It has been tested with a list over 1000 city streets and had an acceptable performance, even on a not so modern machine. There is a minimum of two characters before a search will start. this helps reduce the number of matches shown after any given keystroke. This limit can be adjusted easily.

    When the page loads, a function called fillit() is called.

    //initialize some global variables
    var list = null;;
    function fillit(sel,fld)
    {
            var field = document.getElementByid(fld);
            var selobj = document.getElementById(sel);
            if(!list)
            {
                    ar len = selobj.options.length;
                    field.value = "";
                    list = new Array();
                    for(var i = 0;i < len;i++)
                    {
                            list[i] = new Object();
                            list[i]["text"] = selobj.options[i].text;
                            list[i]["value"] = selobj.options[i].value;
                    }
            }
            else
            {
                var op = document.createElement("option");
                var tmp = null;
                for(var i = 0;i < list.length;i++)
               {
                    tmp = op.cloneNode(true);
                    tmp.appendChild(document.createTextNode(list[i]["text"]));
                    tmp.setAttribute("value",list[i]["value"]);
                    selobj.appendChild(tmp)/*;*/
               }
            }
    }

    A global variable is initialized to null. This will hold an array that in turn holds two custom objects to hold our data. We then get a reference to our select menu and text field objects. If our array does not exist yet (the page has just loaded so it’s still null), then we get the number of options in our select menu, set the contents of the text field to empty and begin looping through the menu contents.

    As we run through each menu option, an object is created that will hold both what is in the value attribute and the text of the option tag.

    If however our list array already exists, we are calling the function in order to refill the menu with all the original data. An option element is created and a temporary container is initialized.

    In the loop the select menu is reconstructed using DOM methods.

    Finding a Match

    The findIt() function does the searching. It accepts two arguments. The first is the name of the select menu, the second is the name of the text field.

    function findit(sel,field)
    {
            var selobj = document.getElementById(sel);
            var d = document.getElementById("display");
            var len = list.length;
            if(field.value.length > 2)
            {
                    if(!list)
                    {
                            fillit(sel,field);
                    }
                    var op = document.createElement("option");
                    selobj.options.length = 1
                    var reg = new RegExp(field.value,"i");
                    var tmp = null;
                    var count = 0;
                    var msg = "";
                    for(var i = 0;i < len;i++)
                    {
                            if(reg.test(list[i].text))
                            {
                                    d.childNodes[0].nodeValue = msg;
                                    tmp = op.cloneNode(true);
                                    tmp.setAttribute("value",list[i].value);
                                    tmp.appendChild(document.createTextNode(list[i].text));
                                    selobj.appendChild(tmp);
                            }
                    } 
            }
            else if(list && len > selobj.options.length)
            {
                    selobj.selectedIndex = 0;
                    fillit(sel,field);
            }
    }

    The first step is to get references to the select menu and the text field. We also need the length of the list array.

    If the number of characters in the text field is greater than 2 and the list array exists. Then the menu is cleared of it's content to prepare it for display of any matches. The number of options is set to one rather than 0 to allow for an option that is always there such as a “Select a Street” option.

    A regular expression object is then created that will be used to look for a match at the beginning of a given string. Using this object to create a regular expression allows the use of a string from whatever source we wish to be used along with any regular expression characters. The first parameter in the object constructor is the regular expression the second is any flags such as "i" for making the search case insensitive. If you were searching something other than one or two word street names, state names or country names you would want to match the beginning of word boundaries using "\b" instead of "^".

    A few utility variables are initialized and we then loop through each of the list items contained in the arrays. If there is a match, the values are used to fill a new copy of the option element we created before the loop started. One thing to note about setting the properties of option elements is that the text label of an option is not an attribute. You must use the optionelement.text syntax rather than setAttribute to set the text label for each option.

    If the length of the text in the field is less than 2 characters then we need to determine if the list needs to be refilled with all the values. By doing this, you allow the user to give up on their search before typing more than two characters and manually select something from the menu if they wish. If the user selects the text in the field and clears it to start a new search this will trigger that action. The fillit function is called and the select menu is refilled.

    Possible Mods

    To make this script and user interface more like the auto-complete widget in a browser address bar, you could use a DHTML menu and provide keyboard control for selecting a match and updating the content in the text box with the selected match.

    This script would allow searching in any array of information and with a little modification any HTML collection. Searchable FAQ's, API documentation or help systems could be achieved by searching content contained in a hidden IFrame, the main HTML document itself or an XML document loaded in the background using the HTTPRequest object.

    Conclusion

    As you can see using auto-complete widgets on a web site can allow a visitor quick access to information. Always be on the lookout for ways to improve the user experience for your visitors and they will continue to come back for more.


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

    More JavaScript Articles
    More By Chris Root

     

    IBM® developerWorks developerWorks - FREE Tools!


    NEW! A Layered approach to delivering security-rich Web applications

    As businesses grow increasingly dependent upon Web applications to provide services to customers, employees and partners, these complex applications become more difficult to secure. Although traditional security solutions protect Internet infrastructure layers, they do not guard against HTTP and HTML attacks. Many organizations that conduct security testing still deploy applications that allow attackers to manipulate their logic and wreak havoc on their business. To mitigate this risk, development and delivery teams must address Web application security throughout the lifecycle, addressing the many layers detailed in this paper.
    FREE! Go There Now!


    NEW! Best practices for software analysis: An introduction to the IBM Rational Software Analyzer application

    This whitepaper presents the benefits of successfully introducing static analysis into your organization using IBM Rational Software Analyzer. Additionally, it identifies some common pitfalls that can hinder the effective use of static analysis tooling as well as presents 10 simple strategies designed to help you quickly realize the value of static analysis using Rational Software Analyzer.
    FREE! Go There Now!


    NEW! Download IBM Rational Developer for System z

    Download a free trial version of IBM Rational Developer for System z, software that can help you deliver core development capabilities; the power of Java Platform, Enterprise Edition (Java EE); and rapid application development support to diverse enterprise application development teams. With comprehensive development tools to help create, deploy and maintain traditional enterprise and composite applications, Rational Developer for System z enables developers with different technical backgrounds to easily participate in important technology projects.
    FREE! Go There Now!


    NEW! Evaluate IBM Rational Developer for System i V7.1

    Download a free trial version of IBM Rational Developer for System i V7.1, which provides a complete development environment for traditional i5/OS application development. IBM Rational Developer for System i is a new eclipse-based workstation offering for i5/OS application development that provides a comprehensive Integrated Development Environment for edit/compile/debug of traditional RPG/COBOL/C/C++ i5/OS applications.
    FREE! Go There Now!


    NEW! Project and Portfolio Management Executive Resource Kit

    Portfolio Management is about effectively managing portfolio value by aligning portfolio investments with business goals. This complimentary e-kit provides a collection of materials that can help you understand how IBM Rational enables and automates best practices for improved governance and clear visibility into portfolio and project performance across the entire IT project lifecycle.
    FREE! Go There Now!


    NEW! Rational Talks to You: Scott Ambler on being agile in a global development environment

    Join this Rational Talks to You teleconference on December 6 at 1:00 pm ET to participate in an agile application development discussion and get your questions answered on using IBM Rational Method Composer in a distributed environment.Get your questions answered!
    FREE! Go There Now!


    NEW! Trial download: IBM Lotus Forms V3.0

    Get a free trial download of IBM Lotus Forms V3.0 (formerly Workplace Forms), which provides a zero-footprint eForms solution to help you automate and move forms-based business processes off the desktop and onto the Web. With Lotus Forms, you can extend applications beyond the firewall by creating a single electronic form document ready for use in both thick and Web 2.0 thin client format.
    FREE! Go There Now!


    NEW! Try the IBM SOA Sandbox for Process

    Visit IBM developerWorks to try the IBM SOA Sandbox for process. The SOA Sandbox for process focuses on providing a trial environment with the necessary tooling and components required to gain a better understanding of business processes and how to best improve existing business processes to derive value quickly.
    FREE! Go There Now!


    NEW! Webcast: Application security testing and Web compliance

    Join the IBM Watchfire team for an informative discussion on techniques and best practices to proactively manage Web application security and how to effectively build application security testing into the software development lifecycle (SDLC). In this Software Delivery Platform webcast you will learn: How to better understand potential web application security vulnerabilities, best practices and how to effectively integrate application security testing into the software development lifecycle, the importance of detecting and removing software vulnerabilities during application development.
    FREE! Go There Now!


    NEW! Webcast: WebSphere Process Server

    WebSphere Process Server delivers a unique integration framework that simplifies existing IT resources. Often, as IT assets grow to support business demand, so too does their complexity and manageability. In this webcast, we’ll discuss how WebSphere Process Server helps deliver an SOA infrastructure that provides a common model to orchestrate, mediate, connect, map, and execute the underlying IT functions. Discover how WebSphere Process Server simplifies integration of business processes by leveraging existing IT assets as reusable services without the complexities of traditional integration methodologies.
    FREE! Go There Now!



    All FREE IBM® developerWorks Tools!

    JAVASCRIPT ARTICLES

    - Using Click Interceptions with a Database-Dr...
    - Using JavaScript Click Interceptions in an I...
    - Using Click Interceptions with JavaScript
    - QuickSort in Action
    - Quicksort
    - Using Mod_Security to Protect Your Server
    - Detecting and Countering Server Intrusions
    - Securing Your Web Server
    - Building a Secure Web Server
    - Protecting the Server
    - Book Review: Learning the Yahoo! User Interf...
    - Dynamically Generate a Selection List in a R...
    - Intergrate DWR into Your Java Web Application
    - Detect Browser Compatibility with the Reques...
    - Using the EXT JS Date Picker Widget






    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 1 hosted by Hostway
    Stay green...Green IT