Tutorial: Create Autocomplete feature with Java – JSP / jQuery
- By Viral Patel on June 8, 2009
- JQuery, Java, Tutorial
Autocomplete is a common feature available in lot of web tools and services. You will find lots of implementation of autocomplete features. Let us see how can we implement a simple Autocomplete feature for Country names in Java-JSP and jQuery.
We will use jQuery’s autocomplete plugin for our example. I have used Eclipse for the development of this demo.
Create a dymanic web project by clicking File -> New -> Project -> Dynamic Web Project and name it AutocompleteExample.

Once the project is created, create a package net.viralpatel.autocomplete and a Java class file DummyDB.java. DummyDB.java is the class that will simulate the database connection and it will provide the data for our example.

Following is the content of DummyDB.java.
package net.viralpatel.autocomplete;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class DummyDB {
private int totalCountries;
private String data = "Afghanistan, Albania, Zimbabwe";
private List<String> countries;
public DummyDB() {
countries = new ArrayList<String>();
StringTokenizer st = new StringTokenizer(data, ",");
while(st.hasMoreTokens()) {
countries.add(st.nextToken().trim());
}
totalCountries = countries.size();
}
public List<String> getData(String query) {
String country = null;
query = query.toLowerCase();
List<String> matched = new ArrayList<String>();
for(int i=0; i<totalCountries; i++) {
country = countries.get(i).toLowerCase();
if(country.startsWith(query)) {
matched.add(countries.get(i));
}
}
return matched;
}
}
The DummyDB.java contains the list of all the countries in a comma separated string value and a method getData () that will return the list of countries starting with the string query passed as argument to that method. Thus if we pass “IN” to this method, it will return as all the countries starting with IN.
You may want to change this code and add the database implementation here. Just a simple “SELECT * FROM <table> WHERE country LIKE ” query will serve the purpose.
Once this is done, we will create the JSP files that will be called by the autocomplete plugin to get the data. Download jquery.autocomplete.css and jquery.autocomplete.js as you will need it in our demo.
Copy jquery.autocomplete.css into css folder in WebContent and jquery.autocomplete.js into js folder.

Create index.jsp and paste following code into it.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/jquery.autocomplete.css" />
<script src="js/jquery.autocomplete.js"></script>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<style>
input {
font-size: 120%;
}
</style>
</head>
<body>
<h3>Country</h3>
<input type="text" id="country" name="country"/>
<script>
$("#country").autocomplete("getdata.jsp");
</script>
</body>
</html>
Update: In above code I have removed the old way of including jQuery library from Google AJAX API and changed it to simple <script> tag.
index.jsp will have a textbox “country” and it calls the server code for doing autocompletion by calling following code:
$("#country").autocomplete("getdata.jsp");
Note that the #country is the id of the textbox where we want to add autocomplete feature and the “getdata.jsp” is the server script that gets called.
Next, Create getdata.jsp and copy following code into it.
<%@page import="java.util.Iterator"%>
<%@page import="java.util.List"%>
<%@page import="net.viralpatel.autocomplete.DummyDB"%>
<%
DummyDB db = new DummyDB();
String query = request.getParameter("q");
List<String> countries = db.getData(query);
Iterator<String> iterator = countries.iterator();
while(iterator.hasNext()) {
String country = (String)iterator.next();
out.println(country);
}
%>
getdata.jsp will just call DummyDB class’s getdata method to fetch list of countries and print it in the response. One thing we need to note here is that the Autocomplete plugin will take input separated by line feed, that is the list of countries should come in separate line. Following can be the desired output:
Denmark Djibouti Dominica Dominican Republic East Timor Ecuador
Execute the code in eclipse and you will get the desired output:

Download WAR file with Source code. (11 kb, war file)
Get our Articles via Email. Enter your email address.



Hello,
This is really a nice piece of code and easy to use, but in my case when i implemented the same piece of code with my JSP its behaviour is changed now when we I open the JSP it showing alert message that \"Internet Explorer cannot open the site\" then my site name and in last \"Operation aborted\".
I am using IE7. Please help me on this.
Thnx
Hi Siddhartha,
I am not sure if this has something to do with browser. I have used jQuery and a plugin which generally are browser independent. I am not about your issue. Can you try running your code in some different browser?
I have not tested this code in IE 7 but I assume it should work. Also check your browsers security settings. In my code, I am trying to include jquery script from google scripts webisite: http://www.google.com/jsapi. You may want to change this piece of code and include your local jQuery javascript.
Hello Viral,
Thnx for your quick reply, I ran the war file which is available on this site, it is running fine. But when i use the same code snippet, some error comes and doesn’t allow to open my site.
Anysways, how can I implement my own jQuery javascript.
please guide me.
You can download jQuery javascript file at http://code.google.com/p/jqueryjs/downloads/detail?name=jquery-1.3.1.min.js and include it in your HTML file with <script> tag:
<script src=”jquery-1.3.1.min.js”></script>
Hope this will work for you.
Thnx viral for the support, I have done what u have written but now it is not finding the google.load() method and if I remove this no error comes but no suggestions come.
What should I use instead of google.load . Please see my code below and guide me what changes I need to do,
google.load(“jquery”, “1″);
input {
font-size: 120%;
}
Country
$(“#country”).autocomplete(“getdata.jsp”);
Try running following code and see if it is running fine. Note that the javascript file needs to be in same directory as your html file as we have included the js directly.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <link rel="stylesheet" type="text/css" href="css/jquery.autocomplete.css" /> <script src="jquery-1.3.1.min.js"></script> <script> $(document).ready(function(){ $("#country").autocomplete("getdata.jsp"); }) </script> <script src="js/jquery.autocomplete.js"></script> <style> input { font-size: 120%; } </style> </head> <body> <h3>Country</h3> <input type="text" id="country" name="country"/> </body> </html>hi…
i have used your countries search code but i have a requirement that when i press key down it should place that value in text field,please provide the solution its urgent.
Thanks and Regards
Santosh
Hi,
I run your war file successfully. But if I change the data string in DummyDB, I am not getting the output.. But U have specified that we can add a select query in DummyDB.java.
Whether the data string in DummyDB.java is changable or not? Please reply.
Yes Dhurai,
The data in DummyDB.java is just for the reference and can be changed. You may also implement your getData(String query) method that returns the matched data. This class is just to demonstrate the functionality. In reality the data will come from database.
Hi,
I am having trouble understanding
String query = request.getParameter(“q”);
How did name the parameter (q) ? Also, how can I add other parameters to send to the servlet?
Thanks
Andy
Hi Andrew, If you noticed, we have invoked the jquery plugin by
$("#country").autocomplete("getdata.jsp");
Thus, this plugin will call getdata.jsp using ajax, whenever user presses a key in textbox and pass the parameter using q as the name of parameter in request. Thus you can get the string entered by user in your script file (in this case getdata.jsp) using q request parameter.
If you want to pass some other argument to the script you do so as follow:
$("#country").autocomplete("getdata.jsp?xyz=123");
In short you have to pass the parameter to script file while calling plugin function.
Hi Viral,
Thanks for your response.
As I understand, “q” is the default parameter passed? All other parameters passed are named in the url string?
Do you recommend using a servlet or using a jsp to produce output? Currently, I’ve set up a javascript version using a servlet.
Thanks
Andy
hello
first, thank you for nice example, i was searching for this for a long time.
but i need a help with my problem. i use same solutions like in this tutorial, but in my jsp i use h:inputText
…
…
So when i want to call jquery autocomplete, id of my component is: $(“#newOrderForm:customer”).autocomplete(“getdata.jsp”);
However, this doesn’t work. It seems that “:” in id is problem.
Can you help me how to solve this?
Hi Matelo,
There seems to be some problem with your jquery selector code ”#newOrderForm:customer”. Try playing with this code and add some text in the DIV and see if it is working.
$(”#newOrderForm:customer”).text(“Hello World”);
If this works than I don’t see any problem why it should not work with autocomplete plugin code.
Yes, you are right, there is problem with selector, because when I try your example and rename “#country” with “#newOrderForm:country”, example doesn’t work.
But i need to address my inputText component, which is inside a h:form. This form has id newOrderForm, so id of my inputText is newOrderForm:customer.
When i don’t use jsf form, but classical html form which is used in example and my id is simple “customer”, everything works fine.
Hi Viral,
Nice tutorial, well explained, clear instructions and images to supplement. Thank you!
Hi Raj, Thanks for the comments.. Feel free to comment on any topic you like and also to subscribe for the feeds or daily articles by email.
Hi Viral Patel,
First I should thank you for such a good article on jquery autocomplete
I have question ,my question is
Is there a way to add name/value functionality to jquery autocomplete
I have recently added the JQuery autocomplete plug in and have a textbox that autocompletes a list of employees. It works great and I commend the authors of the plugin.
I think the textbox would be MUCH more useful though, when upon selecting, we can extract the StaffID (Ie. retreive the value of the selection). My code is below and you can see that I am simply adding the staff names, would be nice to associate IDs.
Does anyone know of any way to do this?
My JQuery:
$(document).ready(function() {
$(\"#tStaff\").autocomplete(\’stafflist.jsp\’);
});
My JSP page:
import=\"autocomplete.TestDB\"
String query = request.getParameter(\"q\");
List codelist= db.getData(query);
Iterator iterator = codelist.iterator();
while(iterator.hasNext()) {
String codeid= (String)iterator.next();
String code= (String)iterator.next();
out.println(code);
}
Here in the JSP code i am fetching staff names and staff id.how can i send staff id to main page.
could you explain with a sample program how to achive the selected value ID.it would great help to me.
Thanks
Continuation for my question
My JSP page:
Here in the JSP code i am fetching staff names and staff id.how can i send staff id to main page.
stafflist.jsp
——————-
page import=”autocomplete. StaffDB”;
StaffDB db = new StaffDB ();
String query = request.getParameter(“q”);
List Staff= db.getStaffData(query);
Iterator iterator = countries.iterator();
while(iterator.hasNext()) {
String staff= (String)iterator.next();
out.println(staff);
could you explain with a sample program how to achive the selected value ID.it would great help to me.
Thanks
hi viral…
nice tutorial… i have a problem when i running in the local server and request data from database…can u guide me to running this tutorial in the local server, please ..
thanks
Hi Eka, You can simply run the above example in your local server. I have used DummyDB class which simulates as if data is coming from DB. You can write your own getData method, fetch data from DB and send it back.
Hi Viral,
I want to send parameters to my servlet .I tried the approach you have suggested in your one of the replies.But that solution is not upto the mark.
For Ex:
To send the parameter-value i have added the code like this
$(“#country”).autocomplete(“servlet/dbFacade?paps=123″);
Now when I have put alert in the makeUrl function in the js to show the url it shows like this
servlet/dbFacade?paps=123?q=
If you see the makeurl has a for loop which loops around extraparams.I beleiev extraparams holds the name value pairs.But I am not sure how to pass them throug the jsp page.
Can you please suggest
Thanks
Annapurneswar
Hello Viral,
nice tutorial – great job.
One hint:
Please update the css code of “jquery.autocomplete.css” from the link “http://www.pengoworks.com/workshop/jquery/lib/jquery.autocomplete.css”. Because right now, the “body” class is missing (but it`s available in the war file).
Best regards,
Markus
Hello Viral ,
First of all thanx for posting such a nice tutorial…
i have a problem i want to display data in the textfield only after the user enters the first three charachters in the textfield as my string contains some 17000 words.
i am not getting where to exactly change in the autocomplete .js it would beb really nice if you could help me out with this
Thanx
Vishal
Hi Vishal, Ideally for such requirement, the code change should be done in autocomplete javascript, but as it is a plugin, we avoid any project specific change in such generic frameworks. What you can do is you can change the Java code or the server side script code that is getting called (in our case getdata.jsp). While retrieving the query, you can neglect the call if the query is less then three characters:
String query = request.getParameter("q"); if(q!=null && q.length() < 3) { return; }Hello Viral ,
thanx for your prompt reply …
but the way u suggested didnt work out properly so i just made a change in autocomplete js
as follows in the function onChange() i just changed the if clause as follows and it is working fine now
if (v == prev || v.length <= 2) return;
prev = v;
Thanx
Hi
This code is very useful to me but I an not able to download
the source code from this site . plz correct the link for download.
Thanks
Dharmendra
Hello Sir,
Even i faced the same issues as Siddharth did reg IE …made changes … but still the functionality is not working fine .. can u pls suggest
Too good.
Works nicely, but copy-pasting the code is pain in the ass since you manually have to delete the line numbers. Also, why is mail required to post a comment?
Hi,
You may want to use Copy option in the code box. Just hover your mouse on code you copy and select Copy option from right side.
Email is mandatory to check the spam :)
Great job! Keep going!
@Vishal Malavia: in the autocomplete plugin there is a predefined set of options, and for your case this might work: $(”#country”).autocomplete(”getData.jsp″,{minChars: 3});
and this should work for extra parameters:
$(”#country”).autocomplete(”getData.jsp″,{extraParams:{xzy:’something’}});
Hi Viral,
Very nice example.I have tried in my example. It is working fine but once i submit the form then it does not work…mean at first time when my html opens it works fine but after submitting the form it is not working…i think the script is not loading at second time. is it?
$(document).ready(function(){ $("#country").autocomplete("getdata.jsp"); })i am getting object expected at this point.
Hi Viral,
After submitting the form, I’m loading the same page and then the script is not working….when i load the page first time at that time it works fine but after wards it does not work…pls help.
Hi Viral,
Yes, it is working fine. Actually path of .js file was wrong in my case..
Thanks …
Hi Viral,
path of java script file was wrong in my example….now it is working fine…thanks..
@Mohit: Nice to see that your error got resolved! Hope you liked the article.
@Tapan: Check if the JavaScript library is properly included in your HTML page. This error will come only if the JS library is not properly included.
Hi Viral,
My path is correct
FollowUp Information
$(document).ready(function(){
$(“#country”).autocomplete(“getData.jsp”);
})
i have included the autocomplete css code in my css.
my jsp and js are same level. what should i check. Please advice
Great work Viral!
Im unable to get the result from my jsp page
Im calling this function on onkeyup event in my textbox but im not getting the data
function funcResult() {
$(“#userName”).autocomplete(“GetSearchResults.jsp”);
}
what could be the reason?
I cant call my jsp page like ur calling..
I have to put jQuery(document).ready(function(){}) only then my page is getting called..
but i dont need that onready functionality..I wud like to call the page only after i start typing in my textbox..
nice piece of code.
but having problem with the real datas from the database. if you can help plz, do.
Hi Viral,
I found following code in jquery.autocomplete.css file. what does it mean??
display:none;/*sorry for IE5*/
display/**/:block;/*sorry for IE5*/
Hi Viral….I have implemented this code in my application….excellent…Thanks…
how to filter data in jsp
Hey Viral,
tNice piece of code. Everything works great but can you give some pointers if I need to use this script with Map rather then List, as I want to show the name of the employee and fetch the employee Id based on that for further processing.
Any help on this will be great help to me… Thanks once Again….
Hi Viral,
I am not sure below issue in your code or I am doing anything wrong, Please advise on the same.
The code works fine, but if you notice when you type any country name, the first member of the drop down is the code e.g “” and then the name of the country start with the desire functionality.
I have deploy this code to bigger HTML and found that the complete HTML part comes as first Element and then the name of the country comes.
Is this the same issue every one else facing? if yes, what will be the work around of this.
Hi, Viral
Great tutorial for dummies.
The thing which made me confused is why we need google’s load method.
and please differentiate between
1. http://www.google.com/jsapi
2. jquery.autocomplete.js
Are they providing different functionality.
PLz rply
Thanx in advance
-Hardik
@hardik: I have removed the old code to include jquery library from google api using load() method. Check the content of index.jsp now. Also the jquery.autocomplete.js is required. This plugin will add the autocomplete feature to our example.
Hi Viral….excellent work…Thanks…,
How to call servlet url in autocomplete method instead of calling JSP .
$(“#country”).autocomplete(“getdata.jsp”);
Could you please give me suggestion to solve this issue.
My sample code
$(document).ready(function() {
$(“#country”).autocomplete({
url: ‘/WelcomeServlet’,
minChars: 1,
max: 10,
width: 10,
scroll: false
}
);
alert(“Ready Function “);
})
……………..
In web.xml
WelcomeServlet
com.cog.AutoServletExample
WelcomeServlet
/WelcomeServlet
It is not invoking the servlet.
Thanks in Advance.
Hi Viral….great code..Thanks,
Your code only show cases which start with the query.
Where should I change your code to accept all the cases which contain the query not just start with?
Thank you so much.
I second that question by Vishnu.
brilliant work. keep posting more.
I’ve tested it with Struts action class instead of calling jsp. It works fine. Simply pass the struts action class url. As stated in API, jquery would append parameter ‘q’ containing the current search value.
Thank you all.
Hi Viral,
Thanks for your great help. I have used your code and it is working successfully.
I am facing a problem like i am using onblur function of JSP on field for which i am using your script (autocomplete). In such case when i use up-down arrow of keyboard for selecting value (autocomplete list box) it works perfect but wheni use mouse arrow only the value which is written in text field passes to onblur function (not the complete value which i select from list box arising for autocomplete). please help for such case.
Hi Viral, I created a functionality of dynamic adding rows
using one of your other tutorial that uses for dynamic row adding in a table
var row = table.insertRow(rowCount);
so, I created a sample row of several textboxes and the add row function is working fine.
The question is how to trigger autocomplete for each of the row in one of the column of text boxes.
The id of the text box for the first row that I modeled was “itemNumber”.
Now for the rest of the rows i do not know what and how to trigger the autocomplete?
$(document).ready(function(){
$(“#itemNumber”).autocomplete(“someURL”);
});
This works for the first row’s text box only…
Could you please send how to get and pass the dynamic rowIDs and call autocomplete
a very good tutorial, which came to me in handy, i would like to know if we can change the parameter q to our desired one, if so where should i change the jquery script.
Any ideas?
Nice piece. I tried to run applicaiton but ended up with the following
‘jQuery’ is undefined
Any suggestions?
Many thanks
Hi Viral,
excellent work….!
Plz i need to retrieve data from mysql database can you help me with that.
i’m new to jsp.
Can you provide an example where the autocomplete works with a primary key and value combination. Only the value must be shown, but the primary key is returned to the web page when the value is chosen.
Thanks
very nice example,i appreciate it ,but can u just tell me where is the callback function?
hi sorry but
i find this error for your application
An error occurred at line: 8 in the generated java file
Only a type can be imported. net.viralpatel.autocomplete.DummyDB resolves to a package
Une erreur s’est produite à la ligne: 5 dans le fichier jsp: /getdata.jsp
DummyDB cannot be resolved to a type
2:
3:
4: <%
5: DummyDB db = new DummyDB();
6:
7: String query = request.getParameter("q");
8:
hi you are here can you help me !!!!
Nicework Viral, in my code, i have populated part description and I need to get the part num also for the same, how do I do it?
Thans for yr code , Nicework Viral, in my code, i have populated part description and I need to get the part num also for the same, how do I do it?
hi Viral
thank for your help
but i have a problem as same as @Vishnu had written earlier posts could u help me solve it?
best regards
hola querido amigo,buen dia. quisiera porfavor que me expliques la manera de hacer todo eso con acceso a base de datos mysql,soy principiante en eso.te agradezco mucho por tu valiosa ayuda. oscar
hello dear friend, good day. please would you tell me how to do all that with access to mysql database, I am beginner in eso.te thank very much for your valuable help. oscar
Hi Viral
Thanks for sharing such a excellent tutorial . It helped me a lot.
Had a small doubt/problem while implementation , The code is working fine the issue is while the data is retrieved from DataBase and displayed in the list I get extra rows as well as extra value “”http://www.w3.org/TR/html4/loose.dtd” which is not there in the DB .
Can you please guide me thru the same .
Thanks in advance.
Hi Viral,
Nice tutorial. But for some reason it’s not working from. Looks like it is not calling getdata.jsp. I am using jquery-1.4.2.min.js do you think that is causing the problem?
Thanks in advance!!
i don’t know much about how to implement this and how it works… could someone help me understand, my general understanding is quite gd, just not when it come to java. I’m using PHP, Mysql and Apache. i have an idea of what needs to be done just I know these things are finiky and if someone could walk me though the process i would be grateful