Apr 15

Easy JavaScript Autocomplete / Intellisense Script

I occasionally run into situations where it would be really great to add an ‘intellisense’ feature to a text input on a web form. That is, something along the lines of AutoComplete or Google Suggest.

There are a bunch of scripts available on the Internets to handle this for you, but they all do things their own way, and they’re never exactly what yor want. I’m always running into the same problems with them:

  • Only works in IE. Bye.
  • Big hairy mass of code. The usual situation is that I want to customize some element of the script’s behavior, but the code is so dense and obtuse that I can’t make changes without breaking things.
  • No documentation. A big hairy mass of code is even harder to deal with if you don’t know what it’s supposed to do in the first place.

So, I finally broke down and wrote my own script. It may not be better than what’s out there, but hopefully it’s easier to understand.


Comments

by danielcole,   April 15, 2005 5:48 PM  

Looks Great in Firefox/Linux. Thank You for the code!


by Dave,   April 15, 2005 7:51 PM  

It kinda works in Safari and FireFox in OS X; type in a letter or two and you get a list, but the arrow keys don't do the trick. You either need to keep typing or pick from the list with the mouse.


by Alejandro,   April 15, 2005 8:13 PM  

Just what I needed. Simple and to the point. MANY thanks.


by Brian,   April 15, 2005 10:36 PM  

great work!


by Simon Willison,   April 16, 2005 9:18 AM  

That's a nice script. There's a bit of a usability flaw though in the fact that hitting "enter" doesn't select the currently highlighted item (it submits the form instead) - hitting tab isn't nearly as intuitive.


by Peter,   April 16, 2005 12:23 PM  

Wow, I was just about to plunge into this XMLHttpRequest thing and this server as a great example. Thanks!


by Jeff Lundberg,   April 17, 2005 7:58 PM  

Next step: Ajax support. :)


by Joe,   April 17, 2005 10:04 PM  

Ajax support would actually a pretty simple addition. This time around, I had a static list of only a few thousand items, so round-tripping the server was overkill. It was the right architecture decision, but not supporting the latest buzzwords means that the cool kids won't let me sit at their table in the lunchroom. :-)

There's a function called getEligible that gets called to read the user input and build an array of eligible suggestions that will be used to build the div. Right now that function just loops an array to find its suggestions. Replace that with an xmlHttp call, and you can slap an official Ajax®logo on it.


by Roger,   May 12, 2005 11:39 PM  

The script is great, but it has some problem when you're typing capital letter by using Shift. I suggest to add a variable for SHIFT: var SHIFT = 16; and then add a case for keyUp: elem.onkeyup = function(ev) { var key = me.getKeyCode(ev); switch(key) { //The control keys were already handled by onkeydown, so do nothing. case SHIFT: case TAB: case ESC: case KEYUP: case KEYDN: return; default: if (this.value != me.inputText && this.value.length > 0) { me.inputText = this.value; me.getEligible(); me.createDiv(); me.positionDiv(); me.showDiv(); } else { me.hideDiv(); } } };


by Theo Larrieu,   May 31, 2005 10:48 AM  

Thanks for the great example code. Here's an enhancement.

I have forms where input can contain comma/space separated list and I wanted auto-suggest for each item, not the input as a whole.


// A holder for prior string in cases where multiple values are used
this.preserveStr = new String();

// Add two new keycode constants
var COMMA = 188;
var SPACE = 32;

//Add to switch statement in onkeydown function

            case COMMA:
            me.hideDiv();
            break;

            case SPACE:
            me.hideDiv();
            break;

// Change the if statement in onkeyup to

        if (this.value != me.inputText && me.getMatchStr(this.value).length > 1)
        {
            me.inputText = me.getMatchStr(this.value);
            me.getEligible();
            me.createDiv();
            me.positionDiv();
            me.showDiv();
        }

//Add a new function getMatchStr
    /********************************************************
    Offer Suggestions for each item in a comma/space separated
    list.
    ********************************************************/
    this.getMatchStr = function(inputStr)
    {
        var regex = /[\s,]/;    
        var finalStr = new String();

        if (inputStr.match(regex))
        {
            matchArray = inputStr.split(regex);
            finalStr = matchArray[matchArray.length-1];
            this.preserveStr = inputStr.substr(0,inputStr.length - finalStr.length);
            return(finalStr);
        }
        //If no special handling, the original string is good enough
        return(inputStr);
    };


//Finally alter the useSuggestion function to

this.elem.value = this.preserveStr + this.eligible[this.highlighted];


by Joe,   June 1, 2005 12:36 AM  

Thanks for the submissions, guys. A number of people have sent me emails with hacks as well, and I wound up writing an "Ajax" version for a project I worked on. Sometime in the next few weeks I'll try to compile up everyone's suggestions into a new package, and perhaps even a new version of the code.


by Joe,   June 7, 2005 9:52 AM  

Just to update, since I've received quite a few emails: I'll try to get a new version of autosuggest put together by next Monday (6/13). I'd like to incorporate all of the suggestions that have been posted, without making the code too confusing, since the whole idea of this script is 'hackable'. You guys have provided a lot of great submissions.

This thing is sort of a little project now, so I'm not sure how to best hand it over to the community. A wiki? A Trac site? I'm open to suggestions.


by Eric,   June 15, 2005 3:18 PM  

I'd love to see your changes. I've started adding some performace changes to it as well and would love to return my contributions once I'm sure they are stable.

How about putting the project up on SourceForge where developpers can access it via CVS (I know - just a couple of files, but still.... ) and make their changes. And you can still maintain control of it.


by Paul,   June 23, 2005 1:22 PM  

What about a field that keeps track of an index in the main array? So you know which item the user selected. (Can't look through the array based on strings because there might be duplicates)


by Aaron,   June 24, 2005 12:23 AM  

This is a great little script. I"m anxious to see the AJAX code because I have run across your site in researching that exact solution.

Let me know if you need any help.


by Paul,   June 24, 2005 1:21 PM  

There seems to be a bug with the div window not popping up when typing too fast...does anyone else get this?


by jigaruu,   June 29, 2005 3:05 AM  

I am unable to download the proper ZIP file, so if some one emails me the script at jigaruu@indiatimes.com id, i will be thankful to them,

Regards, jigaruu....


by tom drellishak,   July 5, 2005 3:28 PM  

I am getting an error while tring to unzip the download files. Its telling me the zip file is corrupt. Can someone send me a good copy?

tom@drellishak.com


by Tristan,   July 15, 2005 7:42 AM  

same error for me :/


by Ben,   August 3, 2005 3:14 PM  

If the download link is still broken, you can grab the javascript source from http://gadgetopia.com/autosuggest/autosuggest.js


  • There are 56 comments on this entry.
  • 20 comments have been displayed above.
Load the next 20 comments.

Add Comment


Want to advertise on this site? Contact FM.
Web Hosting Web hosting, dedicated servers and Web design services
Laser Toner Cartridges UK laser toner, toner cartridges, hp toner, lexmark toner, samsung toner, canon, toner, epson toner, oki toner, kyocera toner, xerox toner, remanufactured toner, compatible toner
Direct TV Deals Free 4 room direct tv deals. no equipment to buy. free fast professional direct tv installation. this is the best direct tv deal available anywhere.
SEO Article Learn from the experts with our SEO article.
rope light Shopping with birddog distributing, inc., gives you access to the lowest prices, the best customer service and the quickest delivery times possible.
Laptop AC Adapter We offer genuine factory direct replacement AC adapters.
Direct TV Best satellite TV deals.
Direct TV Deals Direct TV programming deals are varied and include packages containing from 50 channels up to over 250 channels.
8mm film to DVD Retain family memories with the only frame by frame digital restoration service in the United States for your 8mm film to DVD today
Rubber Stamp Shop for custom self-inking stamps, hand stamps, address stamps, label stamps, check endorsement stamps, check deposit stamps, date stamps, pre inks, pocket stamps, ink and much more!