Click here to Skip to main content
11,500,413 members (70,338 online)
Click here to Skip to main content

Auto-complete Control

, 16 May 2005 1.5M 15.4K 306
Rate this:
Please Sign up or sign in to vote.
Auto-complete control.
<!-- please do not entitify this javascript code; its for on page demo -->

Introduction

Most auto-complete textboxes may have a reverse effect on end-users. Instead of helping them get things done faster, they get irritated by design flaws made by the programmer. (Admittedly, I've made such design flaws too.)

I got to learn this lesson when designing my first auto-complete edit control, found here[^]. Although it seemingly looks intuitive, I forgot to consider the fact that what if the end-user wanted to type just 'ap' but the 'ple' appears out of nowhere? This means that the end-user would then have to hunt for, and press the delete key.

After seeing how GMail made its auto-complete, I took the idea and implemented my own version of the auto-complete control.

Auto-complete textbox control:

<INPUT id=actb_textbox type=textbox>

  • Timeout: 3000ms
  • Delimiter: ; and ,
  • Options: ('an apple', 'alligator', 'elephant', 'pear', 'kingbird', 'kingbolt', 'kingcraft', 'kingcup', 'kingdom', 'kingfisher', 'kingpin')

How does it work?

The important event that will fire whenever the user press any key is onkeydown. The onkeydown event handles all the normal character input and is in charge of creating the auto-complete list. It also handles keys like 'up', 'down' and 'enter'.

Using the JavaScript regexp() object, the script will run through the array containing the keywords and match them one by one. After which, a DIV will be created dynamically using document.createElement(). Finally, when the user presses the 'Enter' key, the DIV will be detached and the input box updated.

The user can also select the options using the mouse. This is done through three events: onmouseover, onmouseout, and onclick.

How do you implement it into your own textbox?

Firstly, include the .js file into your script:

<script language="javascript" type="text/javascript" 
         src="actb.js"></script>

Next, create an array (in JavaScript) containing the keywords:

customarray = new Array('apple','pear','mango','pineapple', 
         'orange','banana','durian', 'jackfruit','etc');

Apply the widget to your textbox using JavaScript:

actb(document.getElementById('textbox_id'),customarray);

And you're done!

Tweakability

This auto-complete edit control has some customizable features:

/* ---- Variables ---- */
// Autocomplete Timeout in ms (-1: autocomplete never time out)
this.actb_timeOut = -1;
// Number of elements autocomplete can show (-1: no limit)
this.actb_lim = 4;
// should the auto complete be limited to the beginning of keyword?
this.actb_firstText = false;
// Enable Mouse Support
this.actb_mouse = true;
// Delimiter for multiple autocomplete.
// Set it to empty array for single autocomplete
this.actb_delimiter = new Array(' ',',');
// Show widget only after this number of characters is typed in.
this.actb_startcheck = 1;
/* ---- Variables ---- */


/* --- Styles --- */
this.actb_bgColor = '#888888';
this.actb_textColor = '#FFFFFF';
this.actb_hColor = '#000000';
this.actb_fFamily = 'Verdana';
this.actb_fSize = '11px';
this.actb_hStyle = 'text-decoration:underline;font-weight="bold"';
/* --- Styles --- */ 

this.actb_keywords = new Array();

The styles are pretty self-explanatory; tweak the values for best results for your own website. Firstly, the variable actb_timeOut controls how long the auto-complete list's timeout should be (i.e., after x ms, the list will disappear). By default, it is set to -1, which represents no timeout.

Next, the variable actb_lim limits the number of elements the list will show, to prevent over-spamming. If you do not want to set any limit, set it to -1.

Thirdly, the actb_firstText variable determines whether the match with the keywords-array should only start from the first character or if the match can be any arbitrary match within the keyword. For example, if firstText is set to true, then a given string "ello" will match with "hello".

Also, the actb_mouse variable determines whether the control should respond to mouse events. Mouse support works when user clicks on the auto-complete list that appears.

The actb_delimiter variable allows for the much requested multiple auto-complete feature. Set a custom delimiter, or even multiple delimiters like semi-colon (;) or comma (,), and the engine will complete words separated by the given delimiter.

Lastly, actb_startcheck controls the number of characters that must be typed in before the textbox will display the control. Thanks to flyasfly for this suggestion.

Implementations

As of version 1.3, all of the above mentioned are public variables. This can be useful in emulating controls like Google Suggest. When you apply the control to your textbox using the actb function, it returns an object.

Changing the autocomplete list

obj = actb(document.getElementById('textbox_id'),customarray);
// ... after some time ...
obj.actb_keyword = new Array('this','is','a','new','set','of','keywords');

Multiple auto-complete textboxes

obj = new actb(document.getElementById('textbox_id'),customarray);
obj2 = new actb(document.getElementById('textbox2_id'),customarray2);

Multiple textboxes (different options)

obj = new actb(document.getElementById('textbox_id'),customarray);
obj.actb_mouse = false; // no mouse support
obj2 = new actb(document.getElementById('textbox2_id'),customarray2);
obj2.actb_startcheck = 2; // start actb only after 2nd character

Todo

  • Add second array (customarrayDesc) for display description in the list (ex => [an apple: it's an apple] instead of [an apple]. Suggestion by angelo77).
  • Many other features suggested by CPians, some of which might be beyond me at the moment but I'll still try my best!

Tested browsers

  • Internet Explorer 6.0.28
  • Mozilla Firefox version 1.0.3

Finally...

Thank you to all of you who have supported, modified, and offered your suggestions to the control! I'm extremely apologetic for the inactiveness of this project because of schoolwork etc. However, I still try my best to work on it whenever anyone has a new feature request!

License

This control will be, from effect of version 1.1, published under Creative Common License [^]

Change Log

  • 1.31: 12/5/2005
    • Fix: Fixed a bug with actb_bgColor styles due to typo.
    • Fix: Now caret does not move away (Firefox) when user presses Enter or tab.
  • 1.3: 8 May 2005
    • Added: actb_startcheck has the number of characters that start the widget control. Thanks to flyasfly for suggestion.
    • Change: All 'tweakabilities' and styles have been changed to public variables.
    • Fix: Fixed an IE-specific bug which prevents the caret position of textarea to be retrieved. Now widget works for textarea too.
  • 1.2: 9 Apr 2005
    • Change: Converted the code of actb widget to OOP.
    • Fix: Mouse click bug that disallows autocomplete control from deleting itself.
    • Added: the keywords array (actb_keyword) becomes a public variable, so it can be modified from the parent script.
  • 1.1: 6 Dec 2004
    • Fix: Metacharacters escaped before parsing with RegExp.
    • Added: Multiple delimiters.
    • Added: Tab now completes the text like Enter.
    • Change: Now, only an event is needed for the control to work; the rest are attached dynamically.
    • Fix: Bugs with caret position in Firefox: originally, 'up' and 'down' keys changed caret position in the textbox for Firefox. This problem has been rectified.
  • 1.0: 23 Nov 2004
    • Fix: some miscellaneous bugs in mouse support (actb_removedisp() cannot be executed properly).
    • Fix: actb_timeout now works fine with mouse support on.
    • Added: When user moves the mouse over each individual option, the option will be highlighted.
    • Added: Multiple auto-complete! This works even if you're editing previous "fields".
  • 0.9: 6 Oct 2004
    • Fix: A bug concerning clientHeight which apparently Mozilla does not support. Thanks Cameron Smith for pointing out.
    • Added: This control now supports phrases with spaces in between. Thanks to Miguel Vieira.
    • Added: This control has mouse support. Thanks to Alecacct and everyone for the idea.
  • 18 Aug 2004
    • Basic engine created.
    • Article posted!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

zichun

Singapore Singapore
I'm young and cool Smile | :)

Comments and Discussions

 
GeneralSimple update for associative arrays Pin
striderman26-Feb-09 9:02
memberstriderman26-Feb-09 9:02 
QuestionPg up and display list Pin
BenRyder9-Feb-09 3:59
memberBenRyder9-Feb-09 3:59 
GeneralEnhanced Pin
jfsanchez2k1-Feb-09 6:10
memberjfsanchez2k1-Feb-09 6:10 
GeneralAbsolutely flawlessly Pin
evilrafael28-Jan-09 6:54
memberevilrafael28-Jan-09 6:54 
GeneralI need your help Pin
hwlp21-Jan-09 1:50
memberhwlp21-Jan-09 1:50 
GeneralProblems with div tags Pin
ChrLange15-Jan-09 1:40
memberChrLange15-Jan-09 1:40 
GeneralRe: Problems with div tags Pin
ChrLange15-Jan-09 3:25
memberChrLange15-Jan-09 3:25 
Generalshowing the same array of keywords for two different text boxes Pin
velm12311-Jan-09 20:10
membervelm12311-Jan-09 20:10 
AnswerRe: showing the same array of keywords for two different text boxes Pin
Brad Kirby3-Mar-09 11:08
memberBrad Kirby3-Mar-09 11:08 
GeneralRe: showing the same array of keywords for two different text boxes Pin
mandelbrot197023-Sep-09 0:57
membermandelbrot197023-Sep-09 0:57 
QuestionSearch multiple parts of an item? Pin
haroldsaxon10-Jan-09 2:05
memberharoldsaxon10-Jan-09 2:05 
GeneralThank you! Pin
ndkha130-Dec-08 10:26
memberndkha130-Dec-08 10:26 
GeneralScripts interfering with seperate form validation Pin
Concoxide3-Dec-08 10:12
memberConcoxide3-Dec-08 10:12 
General1st Item Focus Pin
Member 190445012-Nov-08 6:05
memberMember 190445012-Nov-08 6:05 
Has anybody found a way to stop the first item being auto selected?

I think this is the biggest floor in the script.

If you type in a word and hit enter it will always populate the textbox with the first item from the list.

This will annoy users who do not want to enter a value from the list Unsure | :~

Sam.
GeneralRe: 1st Item Focus Pin
Member 190445019-Nov-08 4:31
memberMember 190445019-Nov-08 4:31 
GeneralRe: 1st Item Focus - SOLVED [modified] Pin
Concoxide3-Dec-08 8:41
memberConcoxide3-Dec-08 8:41 
GeneralJavaScript Warning Pin
Member 190445012-Nov-08 1:24
memberMember 190445012-Nov-08 1:24 
GeneralRe: JavaScript Warning Pin
Member 190445012-Nov-08 1:31
memberMember 190445012-Nov-08 1:31 
GeneralExcelente Trabajo Pin
jorgetinito11-Nov-08 8:27
memberjorgetinito11-Nov-08 8:27 
GeneralGood Idea Pin
Amir Raoof5-Nov-08 8:57
memberAmir Raoof5-Nov-08 8:57 
Generalactb_lim isn't respected Pin
zqfhpzxuckr2-Nov-08 1:07
memberzqfhpzxuckr2-Nov-08 1:07 
Generalautocomplete textbox Pin
zius07530-Oct-08 21:28
memberzius07530-Oct-08 21:28 
GeneralMatch First Characters of Any Word - (Not any part of the string) Pin
cascharly10-Oct-08 2:58
membercascharly10-Oct-08 2:58 
GeneralRe: Match First Characters of Any Word - (Not any part of the string) - SOLVED Pin
Concoxide3-Dec-08 5:37
memberConcoxide3-Dec-08 5:37 
QuestionMy autocomplete list only ever shows 1 option Pin
oxfordmonty031010-Oct-08 1:47
memberoxfordmonty031010-Oct-08 1:47 
GeneralNeed to populate the list Array from a MySql Query - Help Needed Pin
cascharly8-Oct-08 8:34
membercascharly8-Oct-08 8:34 
GeneralRe: Need to populate the list Array from a MySql Query - Help Needed Pin
oxfordmonty031010-Oct-08 1:20
memberoxfordmonty031010-Oct-08 1:20 
GeneralRe: Need to populate the list Array from a MySql Query - Help Needed [modified] - - SOLVED HERE Pin
cascharly10-Oct-08 2:40
membercascharly10-Oct-08 2:40 
GeneralRe: Need to populate the list Array from a MySql Query - Help Needed [modified] - - SOLVED HERE Pin
kiran Gabhane30-Sep-10 5:22
memberkiran Gabhane30-Sep-10 5:22 
Questioncan we pass two dimensional array in it?? Pin
Jagwinder Walia26-Sep-08 0:58
memberJagwinder Walia26-Sep-08 0:58 
AnswerRe: can we pass two dimensional array in it?? Pin
evilrafael28-Jan-09 6:59
memberevilrafael28-Jan-09 6:59 
General2 Dimensional Array Pin
SBrow17-Sep-08 2:00
memberSBrow17-Sep-08 2:00 
GeneralRe: 2 Dimensional Array Pin
Jagwinder Walia26-Sep-08 19:51
memberJagwinder Walia26-Sep-08 19:51 
QuestionChange font color black to white when moving over the list Pin
ashrithos9-Sep-08 6:18
memberashrithos9-Sep-08 6:18 
GeneralExcellent Pin
asilkumar4-Sep-08 23:36
memberasilkumar4-Sep-08 23:36 
GeneralWow Pin
josemaocu22-Aug-08 4:06
memberjosemaocu22-Aug-08 4:06 
GeneralFirst Suggetion Pin
iluindian19-Jun-08 2:00
memberiluindian19-Jun-08 2:00 
GeneralRe: First Suggetion Pin
Jorge Bay Gondra22-Aug-08 3:34
memberJorge Bay Gondra22-Aug-08 3:34 
GeneralRe: First Suggetion - SOLVED Pin
Concoxide3-Dec-08 8:39
memberConcoxide3-Dec-08 8:39 
Generalseems to work on safari 1.3.2 for mac Pin
felix-olivier robert17-Jun-08 8:32
memberfelix-olivier robert17-Jun-08 8:32 
GeneralPlease Help Problems with sql Pin
Paul Hayman6-Jun-08 9:22
memberPaul Hayman6-Jun-08 9:22 
GeneralRe: Please Help Problems with sql Pin
Hanchol7-Jul-08 10:23
memberHanchol7-Jul-08 10:23 
QuestionRe: Newbee Please Help Problems with Javascript/ASP [modified] been up for 24hrs solid.... Cant sleep till it works.. Pin
Paul Hayman1-Oct-10 22:34
memberPaul Hayman1-Oct-10 22:34 
GeneralIs there any alternative in which it displays first element of list in TextBox on key press Pin
Amit Papriwal29-May-08 0:06
memberAmit Papriwal29-May-08 0:06 
GeneralOpen list from javascript Pin
tommcknight23-May-08 11:02
membertommcknight23-May-08 11:02 
GeneralSample application for usage with ASP.NET Pin
Amit Papriwal20-May-08 2:35
memberAmit Papriwal20-May-08 2:35 
GeneralFantastic! Pin
webego29-Apr-08 12:27
memberwebego29-Apr-08 12:27 
QuestionHelp with Thickbox? Pin
Mark Henderson26-Apr-08 17:03
memberMark Henderson26-Apr-08 17:03 
AnswerRe: Help with Thickbox? Pin
Mark Henderson27-Apr-08 5:06
memberMark Henderson27-Apr-08 5:06 
Questioncancel any other event of the textbox Pin
daonly1eng21-Apr-08 12:04
memberdaonly1eng21-Apr-08 12:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150520.1 | Last Updated 16 May 2005
Article Copyright 2004 by zichun
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid