Autocomplete in jQuery

This is my solution for an as-you-type auto-suggest behaviour in an HTML form input, using jQuery. Now, jQuery plugins for doing text input auto-complete are very common and nothing new. However, getting the behaviour right for your particular situation can be tricky with something off-the-shelf. It's also good practice to be familiar with some of the more fundamental parts of Javascript, such as keystroke events.

The code consists of three parts:

  • HTML form, with a couple of text input boxes
  • Javascript code, using jQuery
  • CSS for styling a list of auto-suggest items

In essence, we have one or more text inputs to which we add custom event handlers: keypress, keydown, focus and blur. Both keypress and keydown events need to be captured, so that display keystrokes and control keystrokes can all be interpreted properly. Two control keystrokes in particular to capture are up-arrow and down-arrow, so that we can use them to navigate the list of auto-suggest items instead of clicking on them with the mouse. It's a bit tricky getting the list-item click event to happen before the entire list was hidden; to accomplish this I've added a timer to the input's blur event, so that the list item's click event can still happen; look for setTimeout in the code.

Give it a go

With this in mind, here is my solution which you are welcome to download (click on the code box to the right) and play with*.
You can also test it live, using the text boxes below.

Start typing a name (eg, John) into either of the text inputs below:

    Another name:

      * Disclaimer You can take this code and modify it any way you like. However, by doing so you agree that you use it at your own risk; I shall not be held responsible for its use.


      It's quiet in here...Add your comment