implementing auto complete using jquery
DESCRIPTION
Details step by step walk-through to Implement auto complete using JQueryTRANSCRIPT
Implementing Auto
Complete Using JQuery
Implementing Auto-
Complete Using JQuery
www.dotnetvideotutorial.com
Bhushan Mulmule
www.dotnetvideotutorial.com
Contents
Introduction: ................................
Prerequisite: ................................
What is jQuery? ................................
What is jQuery UI? ................................
Walkthrough 1: Autocomplete in its simplest form:
Important Points to Note: ................................
Walkthrough 2: Reading suggestion list for auto
Important Points to Note: ................................
Important Points to Note: ................................
Walkthrough 3: Displaying More Details in Suggestion List.
Important Points to Note: ................................
.....................................................................................................................
......................................................................................................................
................................................................................................
................................................................................................
Walkthrough 1: Autocomplete in its simplest form: ...........................................................
................................................................................................
ugh 2: Reading suggestion list for auto-complete from database ........................
................................................................................................
................................................................................................
rough 3: Displaying More Details in Suggestion List. ................................
................................................................................................
Page 2 of 19
..................... 3
...................... 3
................................................. 3
............................................. 4
........................... 4
.................................. 7
........................ 8
................................ 11
................................ 14
............................................. 15
................................ 19
Introduction:
This article will help you to implement auto complete functionality for textbox.
understanding article consists of three walkthroughs
Walkthrough 1: Most basic approach to implement auto complete fun
be useful for real project but good place to start with.
Walkthrough 2: This is a realistic example. Auto complete widget calls web service
asynchronously to get suggestion list of employee names from database.
Walkthrough 3: Extends example created in walkthrough 2 to get detail suggestion list
suggestion list will be comprises of Name and City
get displayed on textbox. Also on submission only EmpNo will get submitted.
Examples are demonstrated using Visual Web Developer 2013 Express
can use IDE of your choice, or simply
Prerequisite:
You should have working knowledge of:
1. HTML
2. Little Java Script
3. Basics of jQuery.
Understanding of following topics will be added advantage:
1. Consuming web service using jquery.ajax()
Before starting let us have look on official definitions of jQuery and jQueryUI.
What is jQuery?
In simple words; jQuery is javascript library. That means it is a set of javascript functions that
developer can use for client side processing like validations or animations. It reduces need
of writing complex java script. jQuery also take care of browser
now code without burden of browser compatibility using jQuery.
Official Definition: jQuery is a fast, small, and feature
like HTML document traversal and manipulation, event handling,
simpler with an easy-to-use API that works across a multitude of browsers. With a
combination of versatility and extensibility, jQuery has changed the way that millions of
people write JavaScript.
to implement auto complete functionality for textbox.
rticle consists of three walkthroughs with gradually increasing complexity.
Most basic approach to implement auto complete functionality
be useful for real project but good place to start with.
ealistic example. Auto complete widget calls web service
suggestion list of employee names from database.
Extends example created in walkthrough 2 to get detail suggestion list
comprises of Name and City; but after selecting item only name will
Also on submission only EmpNo will get submitted.
Examples are demonstrated using Visual Web Developer 2013 Express Edition; however you
can use IDE of your choice, or simply notepad☺.
You should have working knowledge of:
Understanding of following topics will be added advantage:
Consuming web service using jquery.ajax()
Before starting let us have look on official definitions of jQuery and jQueryUI.
In simple words; jQuery is javascript library. That means it is a set of javascript functions that
developer can use for client side processing like validations or animations. It reduces need
of writing complex java script. jQuery also take care of browser differences so developer can
now code without burden of browser compatibility using jQuery.
jQuery is a fast, small, and feature-rich JavaScript library. It makes things
like HTML document traversal and manipulation, event handling, animation, and Ajax much
use API that works across a multitude of browsers. With a
combination of versatility and extensibility, jQuery has changed the way that millions of
Page 3 of 19
to implement auto complete functionality for textbox. For better
with gradually increasing complexity.
ctionality. Might not
ealistic example. Auto complete widget calls web service
Extends example created in walkthrough 2 to get detail suggestion list. Now
ut after selecting item only name will
Edition; however you
In simple words; jQuery is javascript library. That means it is a set of javascript functions that
developer can use for client side processing like validations or animations. It reduces need
differences so developer can
rich JavaScript library. It makes things
animation, and Ajax much
use API that works across a multitude of browsers. With a
combination of versatility and extensibility, jQuery has changed the way that millions of
What is jQuery UI?
jQuery UI is build up on built on top of the jQuery library.It
and effects that developer can use on web pages to fasten the development.
date time picker, tab control or auto complete.It is
Ajax controls, as ASP.NET Ajax controls have numerous performance issues.
Official Definition: jQuery UI is a curated set of user interface interactions, effects, widgets,
and themes built on top of the jQuery JavaScript Library. W
interactive web applications or you just need to add a date picker to a form control, jQuery
UI is the perfect choice.
To implement autocomplete we need to include
1. jQuery.js
2. jQuery-UI.js
3. jQuery-UI.css (provides default formatting for jQueryUI widgets)
Walkthrough 1: Autocomplete in its simplest form:
1. Create new empty website using visual studio.
uild up on built on top of the jQuery library.It is a collection of widgets
that developer can use on web pages to fasten the development. For example
auto complete.It is trustworthy replacement for ASP.NET
Ajax controls, as ASP.NET Ajax controls have numerous performance issues.
jQuery UI is a curated set of user interface interactions, effects, widgets,
and themes built on top of the jQuery JavaScript Library. Whether you're building highly
interactive web applications or you just need to add a date picker to a form control, jQuery
To implement autocomplete we need to include following files in our project
(provides default formatting for jQueryUI widgets)
Autocomplete in its simplest form:
Create new empty website using visual studio.
Page 4 of 19
widgets, themes
For example
replacement for ASP.NET
jQuery UI is a curated set of user interface interactions, effects, widgets,
hether you're building highly
interactive web applications or you just need to add a date picker to a form control, jQuery
(provides default formatting for jQueryUI widgets)
2. Add two new folders Style and Script (Right click on AutoCompleteDemo project in
solution explorer �Add �
3. Download jQuery file from
need to right click on latest version link and click on save link as. It will get saved as
jquery-2.0.3.min.js. Add it inside Script folder of project.
4. Download jQueryUI from
was jquery-ui-1.10.3. In case of jQueryUI zip folder will get downloaded extract it.
Add file jquery-ui-1.10.3\
5. Also add readymade autocomplete css file from jquery
1.10.3\themes\base\minified
6. Add new web Form. Example1.aspx
Add two new folders Style and Script (Right click on AutoCompleteDemo project in
� New Folder)
Download jQuery file from http://jquery.com/download/. (To download you may
click on latest version link and click on save link as. It will get saved as
2.0.3.min.js. Add it inside Script folder of project.
Download jQueryUI from http://jqueryui.com/. At the time of writing stable version
1.10.3. In case of jQueryUI zip folder will get downloaded extract it.
\ui\minified\ jquery-ui.min.js to Script folder.
Also add readymade autocomplete css file from jquery-ui-
minified\jquery-ui.min.css to Style folder of project
Add new web Form. Example1.aspx
Page 5 of 19
Add two new folders Style and Script (Right click on AutoCompleteDemo project in
. (To download you may
click on latest version link and click on save link as. It will get saved as
. At the time of writing stable version
1.10.3. In case of jQueryUI zip folder will get downloaded extract it.
.css to Style folder of project
7. After completion of step 3
following snapshot:
8. Drag and drop jquery.js, jquery
Example1.aspx or type following
9. Insert following HTML in body
10. Finally add jquery code in head sectionto implement
After completion of step 3 to step 6 solution explorer should look as shown in
Drag and drop jquery.js, jquery-ui.js and jquery-ui.css files in head section of
or type following
Insert following HTML in body
Finally add jquery code in head sectionto implement autocomplete
Page 6 of 19
shown in
section of
11. Final code should look as follow:
12. That’s it. You can run your first auto complete example. You should get output as
shown in following snapshot:
Important Points to Note:
• languages is a array of strings. We use it as a source for textbox suggestion.
• $("#txtLanguage").autocomplete({ source: languages });
as follow:
That’s it. You can run your first auto complete example. You should get output as
shown in following snapshot:
is a array of strings. We use it as a source for textbox suggestion.
).autocomplete({ source: languages });
Page 7 of 19
That’s it. You can run your first auto complete example. You should get output as
is a array of strings. We use it as a source for textbox suggestion.
o Above line calls autocomplete()
o In this example we are calling autocomplete in its simplest form, where we
are only passing one parameter for
some other variations in next examples. For complete list of you can refer
jQuery-UI API documentation
Walkthrough 2: Reading suggestion list for auto
In the above example we have hardcoded the suggestion list. But in real life we will be
interested in fetching it from database. In
• create database and populate it with some data
• write web Service to fetch data from database
• make use jquery ajax() fuction to call web service asynchronously.
• and use result set as source for autocomplete.
Steps to follow:
1. Add new database “EmpDB”: Right click on project
Server Database
autocomplete() function. This is jquery-ui function
In this example we are calling autocomplete in its simplest form, where we
are only passing one parameter for source flag. i.e languages. We will try
some other variations in next examples. For complete list of you can refer
UI API documentation http://api.jqueryui.com/
Walkthrough 2: Reading suggestion list for auto-complete from database
the above example we have hardcoded the suggestion list. But in real life we will be
interested in fetching it from database. In this walkthrough we will
create database and populate it with some data
write web Service to fetch data from database
jquery ajax() fuction to call web service asynchronously.
and use result set as source for autocomplete.
Add new database “EmpDB”: Right click on project � Add � New Item
Page 8 of 19
function.
In this example we are calling autocomplete in its simplest form, where we
. We will try
some other variations in next examples. For complete list of you can refer
complete from database
the above example we have hardcoded the suggestion list. But in real life we will be
New Item � SQL
2. When you will click on Add button message
App_Data folder for database. Click Yes.
3. EmpDB will be accessible from Server Explorer.
4. Create new table EmpTable
5. Populate it with some records
6. Add connection string to EmpDB database in web.config file.
will be used by web service to connect to database.
(copy and paste connection string property of EmpDB as shown in following
snapshot)
When you will click on Add button message box will pop up asking you to create
App_Data folder for database. Click Yes.
EmpDB will be accessible from Server Explorer.
EmpTable as follow:
Populate it with some records
Add connection string to EmpDB database in web.config file. This connection string
will be used by web service to connect to database.
(copy and paste connection string property of EmpDB as shown in following
Page 9 of 19
box will pop up asking you to create
This connection string
(copy and paste connection string property of EmpDB as shown in following
7. Now let us write web service to fetch suggestion data from database
8. Add new folder “Service”
9. Add web service “SuggestionService” in it
10. After following step 7 and 8 structure should look as follow:
11. To read connection string from web.config file we will need
WebConfigurationManager
will be using ADO.NET to connect to sql server database so add following namespace
import statements in SuggestionService.cs
Using System.Data.SqlClient;
Using System.Web.Configuration;
12. We will be calling this web service from jQuery. By default web service is not
from client script. To make it enable we need to add [ScriptService] attribute on web
service. If you are using visual studio this tag will get inserted when you create web
service but is commented. Just remove comment of following line
[System.Web.Script.Services.
Now let us write web service to fetch suggestion data from database
Add new folder “Service”
Add web service “SuggestionService” in it
After following step 7 and 8 structure should look as follow:
To read connection string from web.config file we will need
ConfigurationManagerclass which resides in System.Web.Configuration
using ADO.NET to connect to sql server database so add following namespace
SuggestionService.cs
System.Data.SqlClient;
System.Web.Configuration;
We will be calling this web service from jQuery. By default web service is not
from client script. To make it enable we need to add [ScriptService] attribute on web
service. If you are using visual studio this tag will get inserted when you create web
service but is commented. Just remove comment of following line
[System.Web.Script.Services.ScriptService]
Page 10 of 19
System.Web.Configuration. Also we
using ADO.NET to connect to sql server database so add following namespace
We will be calling this web service from jQuery. By default web service is not callable
from client script. To make it enable we need to add [ScriptService] attribute on web
service. If you are using visual studio this tag will get inserted when you create web
13. Remove everything inside class SuggestionService. Check
14. Write web method “GetSuggestionList()” as follow:
Important Points to Note:
• GetSuggestionList()
character entered in textbox
Remove everything inside class SuggestionService. Check following snapshot:
Write web method “GetSuggestionList()” as follow:
GetSuggestionList() accepts string pattern. (Which will be sequence of
character entered in textbox on aspx page)
Page 11 of 19
snapshot:
sequence of
• GetSuggestionList() returns
pattern. For example if we enter
“Vanessa” etc.
• WebConfigurationMana
file and assigns it to string variable
• SqlConnection class constructor is using conStr to specify connection string
for object con.
• Two parameters are passed to
i. First is parameterized SQL Query
pattern specified in
ii. Second is SqlConnection object
• cmd.Parameters.AddWithValue()
@InputPattern parameter of sql query.
• In while loop SqlDataReader object
putting it in list object
• And in end list object
15. Now add new page – Example2
16. Add textbox and required links as follow:
GetSuggestionList() returns list of employee names which contains specified
pattern. For example if we enter “sa” it will retrun “sachin”, “sarang
WebConfigurationManager class reads connection string from web.config
it to string variable conStr.
class constructor is using conStr to specify connection string
are passed to SqlCommand contructor.
parameterized SQL Query to select all employee names having
pattern specified in @InputPattern parameter.
Second is SqlConnection object con.
cmd.Parameters.AddWithValue() is passing value in pattern variable to
@InputPattern parameter of sql query.
SqlDataReader object rdr is reading records from database and
putting it in list object result.
And in end list object result is returned.
Example2.aspx.
Add textbox and required links as follow:
Page 12 of 19
which contains specified
rang”,
web.config
class constructor is using conStr to specify connection string
to select all employee names having
is passing value in pattern variable to
is reading records from database and
17. Now add following script in head section:
18. Run the application. And type le output should be as follow:
script in head section:
Run the application. And type le output should be as follow:
Page 13 of 19
Important Points to Note:
• autocomplete() method have t
o source: as we have seen in previous example source should be collection of
strings. In previous example we have hardcoded that string array but here we
wanted to fetch it from database using web service. That’s why we have set
source to suggestionServiceCaller
web service asynchronously and wi
will be used as source.
We can set source to
� array: as done in previous example
� string: when a string is used, the Autocomplete plugin expects that
string to point to a URL resource that will return JSON data
� callback method
flexibility and can be used to connect any data source to
Autocomplete. The callback gets two arguments
response callback method
note that first argument is object while second is callback method and
not an object.
• request object:
• response callback method:
o minLength: minLength flag is set to 2. So autocomplete will wait till you enter
minimum two characters in textbox. Once you enter two characters then only
it will trigger source f
• ajax() function used in suggestionServiceCaller()
(Ajax) request. Here it is responsible to call webservice
the characters entered in textbox as json
of autocomplete() method it has t
method have two flags source and minLength
as we have seen in previous example source should be collection of
In previous example we have hardcoded that string array but here we
fetch it from database using web service. That’s why we have set
suggestionServiceCaller. It is a method which is responsible to call
asynchronously and will receive list of names. This list of name
will be used as source.
We can set source to
as done in previous example
when a string is used, the Autocomplete plugin expects that
string to point to a URL resource that will return JSON data
callback method: The third variation, a callback, provides the most
flexibility and can be used to connect any data source to
Autocomplete. The callback gets two arguments request object
response callback method (explained below). It’s very important t
note that first argument is object while second is callback method and
not an object.
request object:
o Object with single property term.
o term property refers to current value in textbox
response callback method:
o Method with single argument data.
o data is list that is to be suggested to user. It should
depends on term provided
minLength flag is set to 2. So autocomplete will wait till you enter
minimum two characters in textbox. Once you enter two characters then only
it will trigger source function.
suggestionServiceCaller(), performs an asynchronous HTTP
responsible to call webservice asynchronously and
entered in textbox as json. As it is a callback method for
method it has two arguments request object and response
Page 14 of 19
as we have seen in previous example source should be collection of
In previous example we have hardcoded that string array but here we
fetch it from database using web service. That’s why we have set
responsible to call
. This list of name
when a string is used, the Autocomplete plugin expects that
string to point to a URL resource that will return JSON data
The third variation, a callback, provides the most
request object and
very important to
note that first argument is object while second is callback method and
textbox
. It should
minLength flag is set to 2. So autocomplete will wait till you enter
minimum two characters in textbox. Once you enter two characters then only
an asynchronous HTTP
asynchronously and passes
for source flag
response
callback method as mentioned above.
described below:
o url: web service url
o data: data to be post to server
o datatype: specifying that request is passing json data
o type: type is set to post as we are posting data to server. request.term has
data entered in textbox to be posted.
o success: callback method which should get executed if request is successful.
It accepts data from server. this data is the
service. Inside success callback method we call
data to it. Which will be used by autocomplete() widget as a suggestion list
and will get displayed using default css rul
second argument for source callback method of autocomplete.
o error: callback method which will get called if request fails.
Walkthrough 3: Displaying
In this walkthrough let us extend our previous example to see more details in suggestion list
also to specify submission value.
In previous example if we will type
“rajesh”. In this case we would lik
between two items.
as mentioned above. To configure request its using various flags
web service url
data to be post to server in json format.
specifying that request is passing json data
type is set to post as we are posting data to server. request.term has
data entered in textbox to be posted.
callback method which should get executed if request is successful.
from server. this data is the suggestion list return by web
. Inside success callback method we call response() method
data to it. Which will be used by autocomplete() widget as a suggestion list
and will get displayed using default css rules. Remember that response is
second argument for source callback method of autocomplete.
callback method which will get called if request fails.
Displaying Extra Details in Suggestion List.
In this walkthrough let us extend our previous example to see more details in suggestion list
also to specify submission value.
In previous example if we will type “ra” it will give you result as follow as there are two
In this case we would like to see some extra details in suggestion list to distinguish
Page 15 of 19
To configure request its using various flags
type is set to post as we are posting data to server. request.term has
callback method which should get executed if request is successful.
return by web
response() method and pass
data to it. Which will be used by autocomplete() widget as a suggestion list
response is
In this walkthrough let us extend our previous example to see more details in suggestion list
it will give you result as follow as there are two
to distinguish
In this walkthrough let us extend our example to
keep in mind that city should be s
particular item only name should get displayed on text box.
This can be achieved as autocomplete
• First one is array of strings
[ "Choice1", "Choice2" ]
• Second is suggestion list with
[ { label: "Choice1", value: "value1" }, ... ]
• label: The label property is displayed in the suggestion menu
• value: The value will be inserted into the input element when a user selects an
item
Also in real world we wanted to submit id of selected item to server. That can be achieved
by specifying id property in suggested item object. Then this property can be used in
callback method specified for select flag
triggered after selecting specific item from suggested list.
Follow the steps to implement it:
1. Add new class SuggestionItem in App_Code folder.
let us extend our example to display name and city in suggestion list. But
keep in mind that city should be shown in suggestion list only and when we will select
particular item only name should get displayed on text box.
autocomplete() supports two formats for suggestion list
array of strings. That we have used in previous examples
[ "Choice1", "Choice2" ]
list with object having two properties viz label and
[ { label: "Choice1", value: "value1" }, ... ]
The label property is displayed in the suggestion menu
The value will be inserted into the input element when a user selects an
Also in real world we wanted to submit id of selected item to server. That can be achieved
by specifying id property in suggested item object. Then this property can be used in
select flag of autocomplete(). Select callback method will get
specific item from suggested list.
Follow the steps to implement it:
SuggestionItem in App_Code folder.
Page 16 of 19
in suggestion list. But
when we will select
suggestion list
label and value.
The value will be inserted into the input element when a user selects an
Also in real world we wanted to submit id of selected item to server. That can be achieved
by specifying id property in suggested item object. Then this property can be used in
method will get
2. Add three automatic properties
3. Modify service as shown in following snapshot
ic properties in SuggestionItem class as shown in snapshot
Modify service as shown in following snapshot
Page 17 of 19
in SuggestionItem class as shown in snapshot
4. Go to Example.aspx. And insert label to display EmpNo of selected item as shown
below:
5. Insert select flag to autocomplete widget to specify
after selecting an item.
6. Execute the application.
7. Now autocomplete should show name and city in suggestion list as follow:
Go to Example.aspx. And insert label to display EmpNo of selected item as shown
Insert select flag to autocomplete widget to specify callback method to be triggered
Now autocomplete should show name and city in suggestion list as follow:
Page 18 of 19
Go to Example.aspx. And insert label to display EmpNo of selected item as shown
callback method to be triggered
Now autocomplete should show name and city in suggestion list as follow:
8. Also after selecting particular item only name should be displayed in textbox and
also select callback should display EmpNo in label.
Important Points to Note:
• Class SuggestionItem is created with three properties:
• Web service is modified to return list of
• result is object of List of SuggestionItem
• SQL Query is modified to read EmpNo, Name and City
• Inside while loop object of
datareader object rdr is assigned to properties of SuggestionItem object. And then
this object is added to list result.
• After completion of loop i.e after reading all the records satisfying
object result is returned.
• In autocomplete widget only one modification is done
item on label. This is done using
• Select callback method has
selected object in textbox. Using this reference we can access
object.
Also after selecting particular item only name should be displayed in textbox and
ct callback should display EmpNo in label.
Class SuggestionItem is created with three properties: id, label and value
Web service is modified to return list of SuggestinItem type.
List of SuggestionItem type
SQL Query is modified to read EmpNo, Name and City
Inside while loop object of SuggestionItem is created and relevant values from
is assigned to properties of SuggestionItem object. And then
list result.
completion of loop i.e after reading all the records satisfying the condition; list
is returned.
In autocomplete widget only one modification is done to display EmpNo
item on label. This is done using select callback method.
method has two arguments i.e event and ui. ui has reference to
selected object in textbox. Using this reference we can access id property
Page 19 of 19
Also after selecting particular item only name should be displayed in textbox and
value.
is created and relevant values from
is assigned to properties of SuggestionItem object. And then
condition; list
to display EmpNo of selected
. ui has reference to
id property of item