Chapter 27. Recipe: creating an autocomplete text box
This chapter covers
- Creating an autocomplete text box in ASP.NET MVC
- Using a jQuery autocomplete plug-in
It’s not uncommon for text boxes to automatically suggest items based on what we type. The results are further filtered as we type to give us the option to select an available item with the mouse or keyboard. One of the first examples of this in the wild was Google Suggest, shown in figure 27.1.
This chapter covers the mechanics of implementing autocomplete functionality using the freely available jQuery library. We’ll first describe how to structure the code necessary to enable the functionality. Then, we’ll show you how to style the UI to fit within your application’s look and feel.
A rudimentary implementation of this automatic suggestion feature would be to monitor keypresses and fire off Ajax requests for each one. Of course, this means that a fast typist would trigger many requests, most of which would be immediately discarded for the next request coming in 5 milliseconds (ms). An effective implementation would take into account a typing delay and also provide keyboard and mouse support for selecting the items.