Auto Suggest Box

Notice: I have now built a much better and simpler suggest box as a jQuery plugin which you can see here.

This page shows an example of my JavaScript Auto Suggest Box. It is a normal text input box which, using a custom javascript function, automatically suggest's results as the user types. The mark up is simple and can be seen by viewing the source of this page. However to use it you must provide it with two custom functions of your own, one that provides it with results based on the search text it gives and the second is the function for it to call when the user has selected a result.

The function that creates the results gets passed a search string. It must go off to where ever it needs to retrieve results from and then return an array of objects. The objects can be named anything but must contain two members with the following specific names;

  1. id : The ID of a result item.
  2. text : Descriptive name of a result item.

Then when a user selects one of the suggested results the function you create for dealing with the result gets passed back both the id and text. You may pass custom variables into the onKeyUp event of the text input box, if you do then the arguments array of this function will be passed back to your second function as a third variable.

Check it out by searching for a country in the box below,

The example on this page is just using a static array of country names but you could also get results from a SQL database using C# or something simular.


Download the source here

Tested to work in the following browsers;

  • IE 7
  • FireFox 2.0.0.4
  • Opera 9.21
  • Safari (for windows) 3.0.1

Notes : The only style attributes that the JavaScript is setting is the select tag's position to absolute and making sure it's width is the same as the input box. You need to sort out the rest of the styling and position.

Last Updated : 02 July 2007