Click here to Skip to main content
Click here to Skip to main content

Autocomplete edit control for Javascript

By , 21 Aug 2003
 

Introduction

This is a HTML control which integrates autocomplete into the standard textbox. By adding a few lines of code, you can turn any standard textboxes into a user friendly and a rather powerful control.

How it works

Whenever the user types anything in the textbox, the onkeyup event is fired, and the script calls a function. The current text in the textbox is then compared lexically with an array of strings.

Javascript code

<script>
fruits = new Array('apple','pear','orange',
    'mango','durain','grapes','starfruit');
names = new Array('tom','dick','harry','john','petter','foo','bar');
function autocomplete(n,ac_array){
    if (n.value == "") return 0;
    if (event.keyCode == 8 && n.backspace){
        n.value = n.value.substr(0,n.value.length-1);
        n.backspace = false;
    }

    var r = n.createTextRange();    
    tmp= n.value;
    if (tmp == "")return 0;
    for (z=0;z<ac_array.length;z++){
        tmp2 = ac_array[z];
        count = 0;
        for (i = 0;i<tmp.length;i++){
            if (tmp2.charAt(i) == tmp.charAt(i)){
                count++
            }
        }
        if (count == tmp.length){
            diff = tmp2.length - tmp.length;
            if (diff <= 0) break;
            kap = "";
            for (i=0;i<tmp2.length;i++){
                if (i >= tmp.length) kap += tmp2.charAt(i);
            }
            n.backspace = true;
            r.text += kap;
            r.findText(kap,diff*-2);
            r.select();
            return 0;
        }
    }
    n.backspace = false;
    return 0;
}
</script>

<input name='fruit' type='text' class='textbox' title="Opening" 
    onkeyup="autocomplete(this,fruits)" size="20">
<input name='Name' type='text' class='textbox' title="Opening" 
    backspace='false' onkeyup="autocomplete(this,names)" size="20">

How to use the code

  1. You must define the array of strings which you want to have autocompleted.
    fruits = new Array('apple','pear','orange','mango','durain',
        'grapes','starfruit');
  2. Copy the entire autocomplete function and put it somewhere in your code.
  3. Add the event onkeyup='autocomplete(this,fruits)' in the textbox. Note that the 2nd argument should tally with the array name you defined at 1.
  4. Add the property backspace='false' in the textbox. The backspace property is applicable when a user press backspace in the textbox. It gets very irritating without the boolean; i.e. when the user press backspace, the highlighted characters get deleted, but it will automatically be replaced by the same characters due to the autocomplete.

Todo

  1. I've tested the autocomplete control with an array of size 150. The speed was pretty reasonable on my computer (P3 700Mhz). However, I'm sure the autocomplete function's string-matching algorithm can be further improved upon.
  2. Allow for case insensitive string-matching

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

About the Author

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

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 1memberhsnfrz3 Dec '12 - 1:59 
poor
GeneralMy vote of 1memberRisvile28 Sep '11 - 5:00 
NOT WORKING
GeneralAutoComplete text box using PHP PEAR Classgroupelizas8 Mar '10 - 1:27 
PHP PEAR class can make life much simpler.
Demostrated below is a sample of how PHP PEAR library can be used to implement AutoComplete functionality of a text box.
require 'HTML/QuickForm.php';
$teams = array('Amit','Satyan','Saswat','Chinmoya','Sonali','Kiran','Ansuman','Hemendra');
$form = new HTML_QuickForm();
$element =& $form -> addElement('autocomplete','teams','Favorite Engg Team:');
$element -> setOptions($teams);
$form->display();
?>
Now, save the file in a virtual directory and access it from browser. The text box would be populated with the values hard-coded above.
 
http://www.mindfiresolutions.com/AutoComplete-text-box-using-PHP-PEAR-Class-610.php
Cheers,
Eliza

GeneralMy vote of 2membergopimayiru22 May '09 - 2:06 
It doesn't work with mozilla 3.0.10
GeneralNot workingmemberMember 246109727 May '08 - 22:42 
It does not working in MAC - safari
QuestionAutocompletionmemberPratheesh Rajan4 Oct '07 - 2:17 
I tried to use the above code .But it's not working . Can u help me ???
 
Pratheesh
GeneralIs it possible to view all elements' list on particular character pressmemberanil22kar9 Sep '07 - 21:33 
hello,
 
thanks for helpful article,
 
Can I have a look of all elements in my array list on some event of autotextbox. Or can i have list on entering a character like "*", that will
give complete list.
 
Will be helpful if any one can suggest a way!
 


GeneralProblem with 2 Edit Control !!!membersteeve.leprovost4 May '06 - 3:18 
Hi!
 
I would like to know how I can use this feature with 2 Edit Control.
 
For example :
 
var list_county = new Array('A','B','C');
var list_city = new Array('A','B','C');
 
<input type="text" name="Count" id="county_id" value="" size="32">
<script>
var obj1 = actb(document.getElementById('county_id'),list_county);
</script>
 
<input type="text" name="City" id="city_id" value="" size="32">
<script>
var obj2 = actb(document.getElementById('city_id'),list_city);
</script>
 
it doesn't work Frown | :(
 
Thank you very much for your answer, it's very important for me!
 
If you have an exemple with this feature with this component it'll be very good!
 
Steeve Le Provost
GeneralRe: Problem with 2 Edit Control !!!membertah siah rek ngaran naon deui18 Dec '12 - 7:44 
<script>
var list_county = new Array('A','B','C');
var list_city = new Array('A','B','C');
<script>
 
<input type="text" name="Count" id="county_id" value="" size="32">
<script>
var obj1 = actb(document.getElementById('county_id'),list_county);
</script>
 
<input type="text" name="City" id="city_id" value="" size="32">
<script>
var obj2 = actb(document.getElementById('city_id'),list_city);
</script>

Generalnew versionmemberdavidlars9921 Feb '06 - 9:32 
Hi guys,
 
I'd like to show you my version of autocomplete, and you are welccome to change it.
 
I tested it with IE and works like as expected.
 
supports UP, DOWN, HOME, PAGE UP, PAGE DOWN keys. it should be very easy to add functionality for other browser. haven't tested for bugs though Smile | :)
 
http://www.frozendev.com/temp/auto/frameset.html
 
Cheers
Dave
Generalmozillasussvadd__26 Feb '05 - 4:35 
Great one...
But why doesnt it work in Mozilla?
Anyone found a solution yet?
 
Thanks.
GeneralMuch better...memberpackard7526 Oct '04 - 19:38 
To position the cursor at the end of the line when you press ENTER.
 
After this:
 
if (event.keyCode == 8 && n.backspace)
{
n.value = n.value.substr(0,n.value.length-1);
n.backspace = false;
}
else if (event.keyCode == 46)
{
var r = document.selection.createRange();
r.text = "";
return 0;
}

 
Put, this:
 
else if (event.keyCode == 13)
{
var r = document.selection.createRange();
r.moveStart('character', n.value.length);
r.select();
return 0;
}

 
I'm still looking for multiple autocomplete in the same input text (like the
Outlook's input texts ("to", "cc", "bcc"). When you complete one mail address..
the autocomplete "restarts" but now.. for the second word... Roll eyes | :rolleyes:
 
Thiss will be pretty cool !!! Big Grin | :-D
GeneralRe: Much better...memberzichun27 Feb '05 - 21:35 
you can check out my other script at http://www.codeproject.com/jscript/jsactb.asp[^] which supports what you've described
GeneralNot working with mozillasussAnonymous24 Jun '04 - 6:41 
this does not work with mozilla because it does not have createTextRange();
GeneralTo complete in the hole textrange..sussAnonymous25 Feb '04 - 2:02 
Just
 
var stmp = n.value.split(" ");
var x = stmp.length-1;
var tmp = stmp[x];
 
instead of
 
tmp = n.value;
GeneralErrormemberEmelian17 Jan '04 - 17:34 
Anybody else that receives an error when entering text in the second textbox?
 
The "fruit" -box work fine, but the "name" -box generates the following error:
'tmp2' is null or not an object
GeneralRe: Errormemberzichun17 Jan '04 - 17:55 
Hi Emelian,
 
The error results due to the array 'name'. Apparently, this is a predefined object in Internet Explorer and thus could not be used. It will work fine if you change the code from

name = new Array('tom','dick','harry','john','petter','foo','bar');

to

names = new Array('tom','dick','harry','john','petter','foo','bar');

 
and

<input name='Name' type='text' class='textbox' title="Opening" backspace='false' önkeyup="autocomplete(this,name)">

to

<input name='Name' type='text' class='textbox' title="Opening" backspace='false' önkeyup="autocomplete(this,names)">

 
thank you for pointing out this error
 
regards,
zichun
GeneralRe: ErrormemberEmelian17 Jan '04 - 18:35 
That worked better! Big Grin | :-D
 
Do you have an idea on how to make this code work with unicode characters (east-asian etc)?
 
Best regards
Emelian
GeneralRe: Errormemberzichun17 Jan '04 - 19:22 
sorry I'm not really familiar with unicode encodings and how javascript intepretes the character Frown | :( Perhaps someone who is knowledgable in unicode-javascript integration can give his/her advice?
GeneralMake Case InsensitivesussThe Silverlord4 Sep '03 - 23:16 
Nice script. Change the existing line:
 
if (tmp2.charAt(i) == tmp.charAt(i)){
 

to
 
if (tmp2.charAt(i).toUpperCase() == tmp.charAt(i).toUpperCase()){
 
to help with case insensitive matches.
GeneralRe: Make Case Insensitivememberzichun5 Sep '03 - 5:35 
thank you very much Smile | :)
QuestionHow about a sever control?memberPaul Haley29 Aug '03 - 12:07 
This is cool, but how about wrapping it into a server control to allow it to be used in a more ASP.NET style of coding....
AnswerRe: How about a sever control?memberchenggn8 Apr '06 - 5:22 
Try AutoAssist
GeneralAll OK, but ...memberMandalay23 Aug '03 - 20:45 
if i want to enter "pea" , not "pear" pressing DEL key, contents
are updated to "pear". maybe need some check on what key is pressed...

 
----------------------------
never stop coding.
GeneralRe: All OK, but ...memberzichun24 Aug '03 - 3:35 
You can edit function with the following code from
    if (event.keyCode == 8 && n.backspace){
        n.value = n.value.substr(0,n.value.length-1);
        n.backspace = false;
    }
to:
    if (event.keyCode == 8 && n.backspace){
        n.value = n.value.substr(0,n.value.length-1);
        n.backspace = false;
    }else if (event.keyCode == 46){
		var r = document.selection.createRange();
		r.text = "";
		return 0;
	}

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

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130523.1 | Last Updated 22 Aug 2003
Article Copyright 2003 by zichun
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid