Developing AutoComplete Textbox using ASP.NET AJAX 1.0, Web Service and JavaScript
page 3 of 6
by Jesudas Chinnathampi (Das)
Average Rating: 
Views (Total / Last 10 Days): 61594/ 46


The complete steps required to build an AutoComplete Textbox control are elaborated below.

Exposing a Web Service method to be invoked from Client Side

The following is a partial code snippet for a web service class definition.

Listing 1

[WebService(Namespace = "")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class myServices : System.Web.Services.WebService {

In order to expose the class, "myServices" to be invoked from a client side, all we have to do is insert the following attribute above the class definition.

Listing 2


By adding the above line, the AJAX run time extensions will know that we are going to invoke the methods in the myServices class which is going to be invoked from the client side.

Now the methods defined in the myServices class web service are ready to be invoked from the client side. Let us pay some attention to how we can invoke the methods from client side using AJAX.

Invoking the web service method using AJAX

Any AJAX enabled web page should at least have one ScriptManager tag. One of the collections for this ScriptManager tag is the Services collection. Through this Services collection, we can refer to the asmx file that we are going to invoke. Now allow me to show the syntax for the Services collection.

Listing 3

<asp:ScriptManager ID="ScriptManager1" runat="server">
    <asp:ServiceReference Path="myServices.asmx" />

Using the above code, we can invoke the methods defined in the myServices.asmx from client side.

JavaScript code to invoke a Web Service method

Listing 4

ret = className.methodName(Parameter1, OnComplete, OnError, OnTimeOut);

The above is the syntax to invoke a Web Service method from client side JavaScript code. Parameter1 is the parameter for the method. OnComplete, OnError and OnTimeOut are client side JavaScript function names. For example, the client side function "OnComplete" will be invoked once the asynchronous call to the web service method completes successfully. The function "OnError" will be invoked if the asynchronous call to the method results in any error. And finally, the client side function "OnTimeOut" will be invoked, if the asynchronous call to the method does not complete after a certain timeout. These three functions are user defined functions. So, you can name them to your wish. These functions will look as follows:

Listing 5

function OnComplete(arg) 
  alert (arg);
function OnTimeOut(arg) 
  alert("TimeOut encountered");
function OnError(arg) 
  alert("Error : " + arg);

How does an AutoComplete Textbox works?

Now, using the above technique, let us see how we can implement an AutoComplete Textbox. To begin with, the web service method should receive a parameter. This parameter will be the textbox content that the user will be typing in. The web method can compare against a dictionary of words that matches with the passed in parameter. When I say dictionary, it can be an ArrayList or a database call to get the list of matching words. This can be implemented according to your business logic. For our discussion we will use an ArrayList which holds the possible combination of words. For better performance, a binary search will be performed against the Array. .NET Framework has an inbuilt method called BinarySearch. The only pre-condition to use this method is that the Array should be sorted. Again, we can use the inbuilt Sort method before invoking the BinarySearch method. The web service method will return the closest match for the passed in parameter.

The JavaScript "OnComplete" function will receive the text returned by the web service method. Once we have the text, all we have to do is to assign the text to the Textbox. To simplify, the above discussion can be summarized as follows:

1.    User types in text to the textbox.

2.    The "onkeyup" event for the textbox will fire a client side JavaScript function.

3.    The JavaScript function will invoke the web service method. The typed in text will be passed as a parameter to the web service method.

4.    The web service method will return the closest match for the passed in text.

5.    The JavaScript "OnComplete" function will receive the value returned by the web service method and assign it back to the Textbox.

Selecting the text inside the AutoComplete Textbox

One of the cosmetic features of an AutoComplete Textbox is to select the text in the Textbox. For example, if the value returned by the web service method is "hello," then we have to select the text "hello" inside the Textbox. This can be performed by the following code.

Listing 6

function SelectText(intStart, intLength)
  var myElement = document.getElementById('txtSearch');
  // get reference to the Textbox
  if (myElement.createTextRange)
  // If IE
    var myRange = myElement.createTextRange();
    myRange.moveStart("character", intStart);
    myRange.moveEnd("character", intLength - myElement.value.length);;
  else if (myElement.setSelectionRange)
  // if FireFox
    myElement.setSelectionRange(intStart, intLength);

Invoking the Web Service method only when specific keys are pressed

In order to make the AutoComplete Textbox more user friendly, we should not invoke the web service method for any keys pressed. For example, if the user presses the Backspace, we should invoke the web service method. If we allow, then the user will never be able to delete any text that he/she types in to the Textbox. Key trapping is a very simple process in JavaScript. Using the following line we can capture the ASCII value of the key pressed.

Listing 7


Once we have the ASCII value, we can control which keys should be allowed. Here is a code snippet which performs what we discussed in this section.

Listing 8

intKeyCode = event.keyCode;
// See if a valid key key is pressed such as 0-9, A-Z, a-z, Hyphen, Underscore
if (((intKeyCode >= 48) && (intKeyCode <= 57)) ||  // Numbers 0-9
((intKeyCode >= 65) && (intKeyCode <= 90)) ||  // Upper case A-Z
((intKeyCode >= 97) && (intKeyCode <= 122)) ||  // Lower case a-z
(intKeyCode == 189))
// Hyphen
  txtSearch = document.getElementById('txtSearch').value;
  strOldText = txtSearch;
  ret = myServices.WhatIsNext(txtSearch, OnComplete, OnError, OnTimeOut);
  return (true);
// return false.
return (false);

Web Service method which finds the closest match

Here is the code snippet for the web service method which searches for the closest match for the typed in text.

Listing 9

[WebMethod]public string WhatIsNext(string strText)
  int intIndex;
  string strWord;
  strWord = strText;
  intIndex = Array.BinarySearch(arrItems, strText);
  // if an exact match is found
  if (intIndex >= 0)
    // if an Exact match is found, check the next item in the 
    // dictionary to see if it matches
    if (arrItems[intIndex + 1].Length >= strText.Length)
      if (arrItems[intIndex + 1].Substring(0, strText.Length).ToLower() ==
        strWord = arrItems[intIndex + 1];
        strWord = arrItems[intIndex];
    if ((~intIndex) < (arrItems.Length))
      // when we return the next word, make sure that it is really a closest match
      if (arrItems[~intIndex].Length >= strText.Length)
        if (arrItems[~intIndex].Substring(0, strText.Length).ToLower() ==
          strWord = arrItems[~intIndex];
    return strWord;

View Entire Article

User Comments

Title: sdas   
Name: asd
Date: 2012-10-23 4:50:14 AM
Title: addasd   
Name: adasdadasd
Date: 2012-10-17 1:13:11 AM
Title: 1t   
Name: mmm
Date: 2012-09-13 11:47:03 AM
Title: ijjkhjk   
Name: ansdfdf
Date: 2012-06-13 2:07:05 AM
Title: 2012 NFL jerseys   
Name: NIKE NFL jerseys
Date: 2012-05-20 11:29:49 PM
[/pre]Cheap NFL,NBA,MLB,NHL
[url=]Jerseys From China[/url]
[url=]2012 nike nfl Jerseys[/url]
[url=]cheap China Jerseys[/url]
[url=]Sports Jerseys China[/url]
[url=]NFL Jerseys China[/url]
[url=]NBA Jerseys China[/url]
NHL Jerseys China
[url=]MLB Jerseys China[/url]NFL jerseys For Sale online.All Our Jerseys Are Sewn On and Directly From Chinese Jerseys Factory
[pre]We Are Professional China jerseys Wholesaler
[url=]Wholesale cheap jerseys[/url]Cheap mlb jerseys
[url=]2012 mlb all atar jerseys[/url]
[url= [/url]Cheap China Wholesael[/url]
[url=]Wholesale jerseys From China[/url]
[url=]2012 nike nfl Jerseys[/url]Free Shipping,Cheap Price,7 Days Deliver
We are professional jerseys manufacturer from china,wholesal
sports [url=]Jerseys From China[/url]
[url=]NFL jerseys China[/url]
[url=]NHL Jerseys China[/url]
[url=]NBA Jerseys China[/url]
[url=]MLB Jerseys China[/url]
[url=]China Jerseys[/url],Free Shipping
We are professional jerseys manufacturer from china,wholesal
sports [url=]cheap jerseys sale online [/url]
[url=]2012 nike nfl Jerseys[/url]
[url=]cheap NFL jerseys China[/url]
[url=]NHL Jerseys C
Title: HD   
Name: sam
Date: 2011-01-26 1:20:07 PM
Title: ram   
Name: ramin
Date: 2010-05-29 1:37:37 AM
Title: flaw in code   
Name: arnab
Date: 2010-01-21 5:57:33 PM
this is good but not the best, your autocomplete has the basic flaw that when the user presses enter, it submits the page or if he presses tab the word remains incomplete. Somehoe or other u shud allow the user to type 2 letters of a 10 letter word and so that user dont need to type the rest to keep the text in the textbox. good luck !!!
Title: facebook like autocomplete for   
Name: autosuggestor
Date: 2009-12-10 11:58:44 AM
here is a fully customizable auto complete control (facebook like) for
Title: Tyres Dealer   
Name: Tyres Dealer
Date: 2009-11-16 3:55:53 AM
Wow, I never knew that Developing AutoComplete Textbox. That's pretty interesting…
Title: RE: multiple string return   
Name: martien
Date: 2009-07-09 9:38:00 AM
Comment: chk dis for multiple string returns in suto complete ..very naice article it solves my problem :)
Title: excellent mama   
Name: kanchan
Date: 2009-01-10 6:57:41 AM
keka,nice, thank for giving and explaining the concept
Title: Mr.   
Name: Farrukh Malik
Date: 2008-11-06 8:43:29 AM
Title: Mr.   
Name: Syed Mobarak
Date: 2008-11-05 3:20:17 PM
Nice article. :)
Title: Exemple AutoComplete   
Name: Jafrany
Date: 2008-06-27 3:42:54 AM
Video :

Title: autocomplete   
Name: arun
Date: 2008-04-10 8:19:57 AM
It is realy nice concept for Autocomplete
Title: Developing AutoComplete Textbox using ASP.NET AJAX...   
Name: Balakrishnan
Date: 2008-03-26 3:18:24 AM
Its good and light weight application to use in portal side...
Title: Firefox Issue   
Name: vct
Date: 2008-02-11 5:56:56 PM
a great article, its working fine in IE, but it's not working in Firefox. Is there anything else that I need to do to get it to work in Firefox?
Title: mre description   
Name: eric
Date: 2008-01-02 2:18:48 PM
PLease provide an example by merging everything together
Title: Extended AjaxToolkit Control Autocomplete looks like facebook   
Name: Ray
Date: 2007-12-19 5:03:38 PM
Browsing the website I found this autocomplete control which is exactly like facebook. Someone extended the ajaxtoolkit control to make it function exactly like facebook.

This is the persons blog.

This is where I found it.
Title: Its doesnt working properly   
Name: Thanigaimani
Date: 2007-12-07 5:35:47 AM
Your article is ver nice .thanx but i have one doubt.
I get error in script manager tag,it display error for element script managar is not a known element,this is can occur in compilation time..
tel me how to use script manager tag..


Reply me
Title: Auto Complet WebService Through AJAX   
Name: Nitin Sharma Software Engineer
Date: 2007-12-03 11:21:58 PM
Gud One ..!! :-) :-)
Title: My variation of your code   
Name: Dan
Date: 2007-12-03 1:37:44 PM
okay.. so I took what you made.. and I took code from a pure javascript textbox.. and I created my own based on the style of facebook's.

let me know what you think..

Also, just so you know, OnTimeOut is not used anymore. The timeout is combined in the OnError. Check out this page for more details:
Title: It does not work in ASP Page   
Name: Neerman
Date: 2007-11-29 5:07:16 PM
Hi , I have a textbox in ASP.NET and when I use the code for the textbox, it shows null values
Title: AJAX Technology   
Name: Shailendra
Date: 2007-11-29 2:05:42 AM
Title: helloe   
Name: Devin Yang
Date: 2007-11-27 3:09:59 AM
hello sir i want to get this feature
Title: Re: okay.. I was mistaken.. sort of..   
Name: Das
Date: 2007-11-26 7:05:02 PM

I followed your steps and the autocomplete textbox is working correctly.

The dictionary that I have given in the example is not sorted. In my example, I am sorting the array before finding the next word. Hope this helps.

Title: okay.. I was mistaken.. sort of..   
Name: Dan
Date: 2007-11-26 4:18:25 PM
typing in Apple the first time works..


if you type in Apple, then backspace 5 times, and type in apple again, and repeat this process, you get some strange results.

I've been trying to find a perfect autocomplete solution. I found one, (which ISN'T AJAX) which is close to facebook's but it uses a static list. I'm going to try to combine that solution, with your AJAX one, and hopefully it is the best of both worlds.
Title: It works !   
Name: Das
Date: 2007-11-26 3:36:31 PM
Well, I was able to type in Apple. I will take a look at the Facebook's autocomplete feature ...
Title: doesn't work propery..   
Name: Dan
Date: 2007-11-26 3:09:09 PM
I checked out your demo.. try typing apple.. the second the 1 appears, it changes what I typed to a10.. also it took me 3 times to be able to type beer..

Facebook's autocomplete textbox is one of the best I've ever seen.. perhaps you should model your after that one..

Community Advice: ASP | SQL | XML | Regular Expressions | Windows

©Copyright 1998-2024  |  Page Processed at 2024-06-17 7:30:59 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search