Web-based Type Ahead

Add Type-ahead Functionality to Your ASP.NET Apps

UI Tips

LANGUAGES: VB.NET

ASP.NET VERSIONS: ALL

 

Web-based Type Ahead

Add Type-ahead Functionality to Your ASP.NET Apps

 

By Brad McCabe

 

I grew up in Maryland, and boy was I thankful that it wasn t North Dakota. Now, it isn t that I have anything against North Dakota; it s simply that when I have to select my state from a dropdown list on the Web, I only have to type M twice. If I lived in North Dakota, I d have to type N seven times.

 

What am I talking about? If you are one of the 95% of the people who use Internet Explorer, you know what I am talking about: the lack of type-ahead support. If I go to a dropdown list or a listbox and type MAR , I would not end on Maryland. Instead, I would end up going to Maine, Alabama, and then Rhode Island. If I wanted to get to Maryland, I need to type MM .

 

As users migrate to ASP.NET and Web-based applications from Windows Forms, the loss of type-ahead functionality is one of the most missed features. Although not a showstopper for ASP.NET applications to be successful, it is a huge productivity hit, especially for data entry. The good news is that type-ahead is an easy feature to implement in your applications.

 


Figure 1: Adding Windows Forms-style type-ahead functionality to your ASP.NET-based applications is a simple and easy process.

 

The first step is to create either a dropdown or a listbox on your Web Form. After you ve done that, add one line of code to the page load event:

 

DropDownList1.Attributes.Add("onKeyDown", "typeAhead();")

 

This line of code will hook up the onKeyDown event of the dropdown list or listbox to the typeAhead JavaScript function (we ll look at that function in a minute).

 

We could take this one step further in a full scale application. You might want to write a function that loops the controls on a page and automatically wires up dropdowns and listboxes. This would save you from having to do this for each individual control. You could put this function in a common base class (see my previous article Create a Custom Page Base Class).

 

The sample that accompanies this article provides examples of both approaches (see end of article for download details).

 

After we ve wired up the onKeyDown event to the typeAhead function, we are done with server-side code. The only thing left to do is to set up the JavaScript code. For this example, I ll simply put the script right on the ASPX page to make the code easier to follow. In a production application you would most likely put this in a simple JavaScript file and include it from the base class above with a call to RegisterClientScriptBlock (see my previous article Create and Register JavaScript on the Server).

 

There are many good approaches floating around on the Internet to support type-ahead. However, many of them lack one critical ingredient to make them professional grade: a timer to reset if the user pauses long enough. This approach will tackle that hurdle; if a user pauses for a preset amount of time they, can search for a new value.

 

The first thing we ll do in JavaScript is create a single global object to manage everything about our type ahead. It will have four properties and a reset method. You could easily call the reset method from standalone code, but by including it in a main object you keep all the code in one location:

 

var typeAheadInfo =

 {last:0,

  currentString:"",

   delay:500,

   timeout:null,

  reset:function() {this.last=0; this.currentString=""}

 };

 

The last property will contain the timestamp of the last time the user typed a value. This will work in conjunction with the delay property, which will determine if we should reset the object or not.

 

The currentString property represents the characters the user has typed to date that we are going to match on. If a call is made to the reset function, we ll clear this property and start fresh. This will enable our users to type NO rapidly on the keyboard to go to North Carolina, pause for a moment, and then type MAR to jump to Maryland.

 

With our global storage object set up, we can now start into the typeAhead function. Some browsers on the market today already support type-ahead as a built-in feature, so we need to determine if this is the case or if we need to execute our code. We will do that by checking the IE propriety implementation for eventing:

 

if (window.event && !window.event.ctrlKey) {

 

After we enter our if statement we start by time-stamping the event. We will use this value in the next line to help determine if this is a continuation of a set of keys or if we need to start a new array. If we are within the delay window then we continue processing:

 

var now = new Date();

if (typeAheadInfo.currentString == "" || now - typeAheadInfo.last <

 typeAheadInfo.delay) {

 

Next we create three variables to store the event, the dropdown, or listbox with which we are working, as well as the ASCII key code of the key that was pressed:

 

var myEvent = window.event;

var selectElement = myEvent.srcElement;

var keyCode = myEvent.keyCode;

 

We ll fetch the text value of the item into a variable to compare with the characters that are in our string from the users. We use the text value because most users are comfortable typing in values that they can see. If you wanted your users to be able to use the type-ahead feature on the value, you could change the .text to .value in this line. This would enable a user to type MD to go to Maryland. Another example of this would be in a retail application; a sales user might be more productive typing in a product SKU, but instead you want the text of the dropdown to show the product name:

 

txt = selectOptions[i].text.toUpperCase();

 

We convert the text of the item to uppercase. We do the same thing with the characters a user types in. This allows the type-ahead feature to be case insensitive. Note that lowercase would work fine, if preferred for any reason.

 

If we get a match at the start of our option text, then we clear the timeout and update the last property of our global object and set a new timeout. Once we are finished with the timer housekeeping, set the selectedIndex of our dropdown or listbox to the value i (the counter variable that we used to control the loop of option items). We also cancel Internet Explorer s event bubbling before we exit the function:

 

if (txt.indexOf(typeAheadInfo.currentString) == 0) {

 clearTimeout(typeAheadInfo.timeout);

 typeAheadInfo.last = now;

 typeAheadInfo.timeout = setTimeout("typeAheadInfo.reset()",

   typeAheadInfo.delay);

 selectElement.selectedIndex = i;

 myEvent.cancelBubble = true;

 myEvent.returnValue = false;

 return false;

}

 

That s the bulk of the JavaScript function to enable type-ahead on any dropdown or listbox. As you can see, adding true type-ahead functionality to Web-based controls is a very simple and easy process that will provide your users with a more productive and intuitive user interface. For a complete code example, download the sample files for this project.

 

The files accompanying this article are available for download.

 

Brad McCabe is a consultant with Ajilon Consulting, a leading solutions provider. Brad also has been a systems architect and consultant for several Fortune 500 companies and has been a featured speaker at numerous Microsoft events around the world. His primary interests include ASP.NET, Tablet PC, .NET Compact Framework, and Microsoft s networking technologies. E-mail him at [email protected].

 

 

 

 

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish