Click here to Skip to main content
Email Password   helpLost your password?

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:

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

Tested browsers

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

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
GeneralAuto Complete Textbox in Classic ASP
syam@tnt
1:44 4 Dec '09  
Is is possible take data from database. if possible can you give rply

syam.sundar007@gmail.com
Generalcan I do multi select with your code?
taviram123
4:06 22 Nov '09  
I want to have auto-suggest with multi select box.
can I use your code for this?
Tali
GeneralFantastic
Navin C. Pandit
19:52 1 Nov '09  
Hello Dear,
Really cool n superb.

Thanks lots for sharing
Navin C.
GeneralText box size increases when the text is big
amitsplash
23:48 20 Oct '09  
It automatically increases the size of all the textboxes in the form as per the text length in those textboxes. what is the solution of this.
GeneralDEPRECATED!
egoman69
13:27 8 Oct '09  
This script is no longer under development by zichun. He will not reply to your questions.

Dmitry has a new and better version: Auto-suggest Control[^]
Generalmouse click stops working when ajax used to update list
Member 4523987
2:29 23 Sep '09  
Hi,

I am using ajax to update the list used by actb. When listToShow is populated for the first time,
everything works fine. However, when I get a new listToShow from the database using ajax, and
send it to setupFullSiteList again, the mouse click for autocomplete stops working.

Any idea why ?
function setupFullSiteList(listToShow){
var myActb = new actb(document.getElementById("location"), listToShow, true, 1, "location");
}


Thanks
basm101
GeneralVery useful piece of code...
mandelbrot1970
2:16 23 Sep '09  
Zichun,


Many thanks for posting this excellent code - it is proving invaluable to an application I'm presently writing.


Paul.
Generaluse in commercial website
taurus12345
1:28 23 Sep '09  
hi zi chun,
im a coder in html and php and we re starting a website for a comparison of companys... i dont know if we earn money with that site or not but i prefer to ask u in the way: can i use that script u wrote on a commercial website? (because is licened under cc).. or what du u want?
pls give me an answer cause i need it in the next coming days...

thank u so much Wink

greets from germany
pete
QuestionBorders and fixed-width
Aesculaepius
12:03 17 Sep '09  
Anyone have any ideas on how to set the width for the dropdown to be fixed to my selection box? Also, I'd like to add a border to the dropdown list box, rather than color it. I'm relatively new to JavaScript and while I can do this on a normal div, I'm not there yet if I need to do it via script.

~Asc
GeneralJavascript error
nainakarri
20:51 16 Sep '09  
Hi

Very nice article..... i tried using the same in my web application. But i am getting javascript error "Type mismatch" everytime i press key.

When i tried debugging..........

In the below function

function addEvent(obj,event_name,func_name){
if (obj.attachEvent){
obj.attachEvent("on"+event_name, func_name);
}else if(obj.addEventListener){
obj.addEventListener(event_name,func_name,true);
}else{
obj["on"+event_name] = func_name;
}
}

When the event_name is focus the func_name is undefined in the above function.

the above function is being called from

addEvent(actb_curr,"focus",actb_setup());

function actb_setup(){
addEvent(document,"keydown",actb_checkkey);
addEvent(actb_curr,"blur",actb_clear);
addEvent(document,"keypress",actb_keypress);

}

Kindly help.

Thanks in advance
Naina

Naina

GeneralThanks for the code
basheerpt
0:12 1 Sep '09  
Hi,
Thanks for the autocomplete code. How would i use it against a database (access) search box to get the result?

Thanks for your help
GeneralMinor error
George Farnsworth
12:10 20 Aug '09  
The styles list contains an error.

this.actb_hStyle = 'text-decoration:underline;font-weight="bold"';

The correct style would be:

this.actb_hStyle = 'text-decoration:underline;font-weight:bold;';
GeneralHow to use it in ASP.Net 2.0
hon123456
0:43 6 Aug '09  
Dear Chun,
I can use your actb in html. But I cannot use it in ASP.Net 2.0.
The browser complains "object is needed".How can I use your function in
ASP.Net 2.0. Thanks.
GeneralNice function but difficult to read.
alwyn2
1:53 24 Jul '09  
I have to agree with r3kb. The function works very well and the download is nicely self-contained but the code is very difficult to read. May I suggest the following:

- more documentation in the code, the purpose of each function at the
very least,
- friendly variable names,
- use of line spacing where appropriate to help with ease of reading and
- be kind to your fellow developers by avoiding inlines like this:
"if (actb_self.actb_timeOut &gt; 0) actb_toid = setTimeout(function(){actb_mouse_on_list = 0;actb_removedisp();},actb_self.actb_timeOut);"

Thanks for publishing your code!

- Alwyn

P/S: You might want to put your details in the Javascript files so we can give you proper credit. Wink
GeneralLike it but hard to read
r3kb
22:11 6 Jul '09  
I like the control quite a bit, but I find that the code it's based on is difficult to read. I would hope that a choice would be made to change to code that self-documents more. Over time, I've learned that commenting every line of code is more distracting than helpful. Code that self-documents uses variable and method names that describe what each is used for. IMNSHO, comments are best used to describe intent, nuances, and challenges. Single letter variables are okay for counters in loops, but it's easier to see what the counter is used for if it's descriptive...

Thanks for the tool and the article. I find it useful already, but I can see that in order to incorporate it into what I'm doing, I'll need to make some changes to it.
Cool
GeneralAwesome!
Kdiggins
16:02 29 Jun '09  
I loaded a 25,000+ line job list into your control for the first time today at work.

It works flawlessly!

Thank you for your valuable contribution.
QuestionAutocomplete+dynamically
kamaraju.prathi
5:05 24 Jun '09  
Hi ,
Here the requirement is when i type a letter "A" then it will retrive a set of values from database.Then i should use this auto complete instead getting all the values in an array and showing .Could please reply at earliest.Confused
AnswerRe: Autocomplete+dynamically [modified]
Klaaslievens
0:17 4 Jul '09  
Hi back,

In php, I did it like following, and it's working perfect (although I have a problem with positioning in my thickbox...):

1) retrieve all values from the database and put them in a string (indeed, not a php-array!)

$rs=mysql_query("select name from table");
$aantal=mysql_num_rows($rs);
$i=1;
while(list($name)=mysql_fetch_row($rs))
{ if($i<$aantal) $array_names.="'$name',";
//if it's the last item from the series, don't put a comma after the value
else $array_names.="'$name'";
$i++;
}


2. Put the following at the place where you want to show the values (the php-string will just be echoed in the javascript):

<script>
var customarray = new Array(<<??php echo $array_names; ??>>;
var obj = actb(document.getElementById('names'), customarray);
</script>


And you're done!
I suppose that the approach will be similar in other languages like ASP.

Good luck!

P.S. It seems that this site is blocking the php-tags , so for that reason you have to change the line with 'var customarray' etc. in step 2...

modified on Sunday, August 30, 2009 3:50 PM

GeneralCan't align to left
mark3960
8:38 6 Jun '09  
Could someone tell me how to align my suggestions to the left? I seem to be missing something.

Thanks.Confused
GeneralCross-Browser
Tale Masinov
4:59 28 May '09  
Hi,

I got one question, is this tested on newer browser such as Google Chrome or Safari or it's just IE and Firefox?
I tried it on Chrome and it doesn't work. Am I doing something wrong or it's not supported?

Thanks.
GeneralUpdated control and support [modified]
Dmitry Khudorozhkov
18:02 15 Apr '09  
Author of the article, unfortunatelly, neither develops this control nor provides the support for it; I've taken a liberty to do the either:

Auto-suggest Control[^]

Listen up! "Teamwork" means staying out of my way! (Seifer, Final Fantasy 8).

modified on Tuesday, May 12, 2009 6:57 PM

Generalassociate ID with the array
rzshiplu
21:40 30 Mar '09  
hi,it became really helpful for me.....

but please anyone can help me a little bit ?

The array is generated from DB...
I want to list only the name of the employees in the list.....
and each employee has an ID field in my db....

when I select a name from the list....at the same time can I get the associated ID of the selected employee ?

is it possible ?
Generalnot properly working ie 5
uraj08
19:29 30 Mar '09  
hi

it is not properly working ie 5.

it shows this error. Could not get the cursor property. Invalid argument


thank u
GeneralMouse event does not work
Member 2245288
22:21 8 Mar '09  
Hi,
I use actb for populating names and the names coming is a dynamic list prepared by ajax.
Once the names are populated the actb works fine but as soon as the dynamic list is changed the mouse events stops working..
Please help.....

Thanks
Regards
Vibhu
GeneralSimple update for associative arrays
striderman
10:02 26 Feb '09  
I wanted to use this on decode type arrays, such as

arry["elem1"] = "...."
arry["elem2"] = "...." etc

These types of arrays can be used simply by changing the for loops to use this syntax:

for (var i in actb_self.actb_keywords) {

}


Last Updated 16 May 2005 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010