Tutorial: Create Autocomplete feature with Java – JSP / jQuery

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.

Related: Spring MVC – AutoComplete tutorial with JSON & JQuery

We will use jQuery’s autocomplete plugin for our example. Just go to JQuery Autocomplete UI page and download JQuery UI JS and CSS files. 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.

eclipse dynamic web project

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()) {
		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)) {
		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" 
	<link rel="stylesheet" type="text/css" href="css/jquery.autocomplete.css" />
	<script type="text/javascript" 
	<script src="js/jquery.autocomplete.js"></script>  
		input {
			font-size: 120%;
	<input type="text" id="country" name="country"/>

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:


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.

<[email protected] import="java.util.Iterator"%>
<[email protected] import="java.util.List"%>
<[email protected] 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();

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:

Dominican Republic
East Timor

Execute the code in eclipse and you will get the desired output:

Download Source Code

Java_JQuery_Autocomplete_example.war (11 KB)

Get our Articles via Email. Enter your email address.

You may also like...


  1. Siddhartha says:

    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.


  2. Viral Patel says:

    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.

  3. Siddhartha says:

    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.

  4. Viral Patel says:

    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.

  5. Siddhartha says:

    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%;



  6. Viral Patel says:

    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"
    	<link rel="stylesheet" type="text/css" href="css/jquery.autocomplete.css" />
    	<script src="jquery-1.3.1.min.js"></script>
    	<script src="js/jquery.autocomplete.js"></script>
    		input {
    			font-size: 120%;
    	<input type="text" id="country" name="country"/>
  7. M.Santosh says:

    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

  8. Dhurai says:

    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.

  9. Viral Patel says:

    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.

  10. Andrew Krenitz says:

    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?



  11. Viral Patel says:

    Hi Andrew, If you noticed, we have invoked the jquery plugin by


    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:


    In short you have to pass the parameter to script file while calling plugin function.

  12. Andrew Krenitz says:

    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.



  13. matelo says:

    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?

  14. Viral Patel says:

    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.

  15. matelo says:

    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.

  16. Raj says:

    Hi Viral,
    Nice tutorial, well explained, clear instructions and images to supplement. Thank you!

  17. Viral Patel says:

    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.

  18. Sreenivas says:

    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() {
    My JSP page:


    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();

    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.


  19. Sreenivas says:

    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.
    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();

    could you explain with a sample program how to achive the selected value ID.it would great help to me.


  20. eka says:

    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 ..


  21. Viral Patel says:

    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.

  22. Annapurneswar says:

    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
    Now when I have put alert in the makeUrl function in the js to show the url it shows like this
    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

  23. Markus says:

    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,

  24. Vishal Malavia says:

    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


  25. Viral Patel says:

    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) {
  26. Vishal Malavia says:

    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;


  27. dharmendra says:

    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.


  28. vikram says:

    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

  29. Anindita Banik says:

    Too good.

  30. Name (required) says:

    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?

    • Viral Patel says:

      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 :)

  31. Sergio says:

    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});

  32. Sergio says:

    and this should work for extra parameters:


  33. Mohit says:

    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?

  34. Tapan says:

    i am getting object expected at this point.

    • Viral Patel says:

      @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.

  35. Mohit says:

    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.

  36. Mohit says:

    Hi Viral,
    Yes, it is working fine. Actually path of .js file was wrong in my case..
    Thanks …

  37. Mohit says:

    Hi Viral,
    path of java script file was wrong in my example….now it is working fine…thanks..

    • Viral Patel says:

      @Mohit: Nice to see that your error got resolved! Hope you liked the article.

  38. Tapan says:

    Hi Viral,

    My path is correct

    FollowUp Information


    i have included the autocomplete css code in my css.
    my jsp and js are same level. what should i check. Please advice

  39. JM says:

    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() {
    what could be the reason?

  40. JM says:

    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..

  41. dipendra sunar says:

    nice piece of code.

    but having problem with the real datas from the database. if you can help plz, do.

  42. Mohit says:

    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*/

  43. Senthilkumar MKS says:

    Hi Viral….I have implemented this code in my application….excellent…Thanks…

  44. pawan says:

    how to filter data in jsp

  45. Niket Shah says:

    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….

  46. Niket Shah says:

    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.

  47. hardik says:

    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

    • Viral Patel says:

      @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.

  48. Vishnu says:

    Hi Viral….excellent work…Thanks…,
    How to call servlet url in autocomplete method instead of calling JSP .


    Could you please give me suggestion to solve this issue.

    My sample code

    $(document).ready(function() {
    url: ‘/WelcomeServlet’,
    minChars: 1,
    max: 10,
    width: 10,
    scroll: false
    alert(“Ready Function “);

    In web.xml



    It is not invoking the servlet.

    Thanks in Advance.

  49. GR says:

    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.

  50. Suresh says:

    I second that question by Vishnu.

    brilliant work. keep posting more.

  51. Suresh says:

    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.

  52. ankit says:

    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.

  53. Rajagopal says:

    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?


    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

  54. sai praneeth says:

    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.

  55. Rajagopal says:

    Any ideas?

  56. Ocmalo says:

    Nice piece. I tried to run applicaiton but ended up with the following
    ‘jQuery’ is undefined
    Any suggestions?

    Many thanks

  57. JAK says:

    Hi Viral,
    excellent work….!
    Plz i need to retrieve data from mysql database can you help me with that.
    i’m new to jsp.

  58. Francois says:

    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.

  59. dhaval says:

    very nice example,i appreciate it ,but can u just tell me where is the callback function?

  60. elmahdi badi says:

    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
    4: <%
    5: DummyDB db = new DummyDB();
    7: String query = request.getParameter("q");

  61. elmahdi badi says:

    hi you are here can you help me !!!!

  62. venkat says:

    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?

  63. venkat says:

    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?

  64. saeidlogo says:

    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

  65. Oscar says:

    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

  66. Oscar says:

    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

  67. Sunny says:

    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.

  68. Maria says:

    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!!

  69. Calvin says:

    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

  70. Fayyaz says:

    Hi Viral,
    This is a nice article and helped in understanding autocomplete functionality.
    I have a scenario that you can advise on.
    I am searching users from the database by their name and once the user is selected from the autocomplete dropdown then the user’s name, id and email address are need to be saved upon user clicking the Save button.
    My question is somewhat related to Sreenivas’s question but he didn’t get any answer on that.
    Thanks in advance

  71. Vinod says:

    How to implement the same in JSF?

  72. Rajat says:

    Hi Viral,
    Great piece of code. Works perfectly.

    I have used this with a DB and want to disable caching so that updates are shown directly from DB as they might be changing.

    Presently, the function to retrieve data from DB is only called once i.e. only the first one for every literal/query. I want it to happen everytime even when the same query is entered.

    I tried noCache:true option and even tried removing all cache involving functions from the js but none of it works. Still the DB is queried only once for the same query.

    Kindly help. Thanks in advance.

  73. Brijesh says:

    How to set limit in display record? pls describe syntax for below code
    Hello sir,
    i access record with around one lacs database in jsp struts2, in dojo it become very loaded so,i used jquery autocompleter ,thanxs but i want to limit it in showing record.pls help me
    it is urgent
    my code is below.


  74. Rajat says:

    Hi Brajesh,

    You may use this:

    $(“#country”).autocomplete(“webpages/getdata.jsp”,{maxItemsToShow : 10});

  75. Brijesh says:

    Thank you very much for the help i will try this.

  76. riya says:

    I m facing problem in this example. when i type anything in country textbox. It is not hitting the getdata.jsp. find no error also. please help me

  77. Manish Jain says:

    Hi, Viral, thanks for the tut, but I don’t am not able to work with this. I have made some changes, like to the java file name and instead of using a static one I have used data from my database. When I am pressing a key on the index page, nothing is happening. I have also changed the text field name to security and correspondingly have used $(“#security.”).autocomplete(“getdata.jsp”).
    I have added the js and css file to the location u asked us to keep them at.I have no clue why it is not working. Do I have to download a plugin ot something?

  78. chengaReddy says:

    Hi Viral Patel Thanks
    Iam using IE7 this auto complete script is not supporting in my browser .is it possible to do without using script code . we have some difficult to analyse script .so any simple java code is available? iam using struts2 tag but its not working it showing drowdown only. pls help me any simple way to implementation using java,jsp.
    if u have any idea of struts2 tags is easy to me pls help me…………………….

  79. Hari Ravella says:

    How to call an action instead of getdata.jsp

  80. Brij says:

    Hi Viral,

    Such a nice article. Thanks a lot. Keep it up.

    I just want to know how can I call Ajax to retrieve data.


  81. Vijay says:

    Hi Viral,
    Thanks for nice example on autcomplete functionality. For me code works fine in IE browser but same is not working in mozilla. When i enter a character in the text field I am getting “The ‘charCode’ property of a keydown event should not be used. The value is meaningless.’ warning message. Could you please suggest me how to resolve this issue?

  82. Mohammed says:

    I am working on Strus1.0, can u pls send the code to implement autocomplete in jsp

  83. Karthik says:

    Hi..I am using struts2 and jsp for my project.I am able retrieve data from database onto the action class but I want to get the same onto the jsp page.I am using Mysql and eclipse IDE.Kindly help.Thanks in advance

  84. Irfan says:

    Thanks for the information.
    but when i deployed the war file in eclipse and i then run it on Jboss from index.jsp
    it show me index file with a text box.
    but when i press ‘A’ or any alphabet it does gives any information regarding country name’s starting with ‘A’ .
    in eclipse it show following message
    at java.lang.Thread.run(Unknown Source)

  85. Aditya says:

    Hi Viral,
    I am just beginning to learn autocomplete and jquery.
    1. Can we use struts2 and jquery jar lib to accomplish this?
    2. Can u point out some exam[ple?

  86. prashant says:

    Hi Viral,
    Such a nice article. Thanks a lot. Keep it up.

  87. Michelle says:

    Hi Viral,
    I am having problem during mouse click. I am not getting any data when I select on the dropdown using mouse click but it works fine using arrow keys. Please help. Thanks!

  88. Uma says:

    Hi Viral

    Very Nice Plugin

  89. Mike says:

    Nice tutorial, but I have some problems here, I just have Copied and Pasted all things but when I type a letter nothing happens. I wonder why?

  90. Anderson says:

    Good evening,
    First I would like to congratulate the tutorial because you saved my life.
    I am having trouble connecting using this example in a database.
    I have a table with names of countries worldwide. Where should I put my query so I can get the countries in this table?

  91. James says:

    Great little tutorial. Easy to follow and understand for a java noob like myself.

  92. Ankur says:

    Hi…can any one plz help me in integrating it with Struts2 application…what return type is expected in action class….


  93. ujjawal says:

    any idea how this work like GOOGLE search ,like name is “Hello” if user type “ello” it should display Hello in list

  94. jsphater says:

    This is a nice tutorial. I would add a note of caution however. Doing Java code in JSP is good for a quick demo, but is not a good long term approach. It is not easily unit testable (unless with Selenium) and is not compiled until runtime.
    I am currently using DWR with Jquery autocomplete for this and it works perfect.

  95. Jaana says:

    Can the returned list also be a String like:

    String personList = null;
    List ldapUsers = ldap.getUids();
    for (int i=0;i<ldapUsers.size();i++) {


  96. VRaj says:

    This is very useful also business peoples like me who read from net can easily understand this.Htas of Viralpatel.
    Viral this is good code for single textbox.But if i had 4 textbox and if i select a name from firsttext box i want to get datas for this from DB in balance three textbox.Is it possible.If so please help me.

  97. g says:

    yayaya, me also not working….

    im not sure why it wasn’t worked.
    Even tough mysql command already correct using LIKE statements,
    and the jsp page already corrected to println (line by line).

    Seems the plugin is not fully customized with jquery 1.4.2 version that i’m currently using on right now. Thus, if there’s any updates let me know ya? :D

    Thanks dude!

  98. Saranya Jayaram says:

    Hi Viral,
    Does the autocomplete feature work only in a dynamic web project in eclipse?

    With Regard’s
    Saranya Jayaram

  99. Majid says:

    I run this code in eclipse, it’s not working at all.

  100. Arun says:

    Nice. But only problem here is the machine needs to be in internet :-( Is there any way to resolve it?

  101. dh says:

    it doesn’t work ;(

  102. zide says:

    sorry but it doesnt work …

    • Ravi says:

      I think u would have not concentrated on js and css files, i too done the same mistake, then after rectifying it is working…..

      • Sriram says:

        Hey, can you explain what you did to make it work please?

  103. Daniel says:

    Plain and simple :) it does work…thanks !

  104. Michael says:

    Hey is there an other solution then to out.println(country); ??

    Maybe to return an array from an controller jsp or something else?

  105. anand says:


    From where are we passing this value?

    String query = request.getParameter(“q”);


  106. webBuilder says:

    for some reason when I include

    on my page, other css will break and is not visible the web site as I want it..

    is there any solution for it? thank you

    • webBuilder says:

      I meant when I enclude that script that calles jsapi of the google javascript..

  107. webBuilder says:

    for some reason when I include

    on my page, other css will break and is not visible the web site as I want it..

    is there any solution for it? thank you

  108. jeff says:

    is it possible to tell me how i can add a flag with the county name. :)

  109. Steve Jobs says:

    Fantastic. Thanks a million. Worked perfectly!

  110. Randi says:

    hello viral, i has try your code, but not display data in textbox and no errors. how to solve??

  111. Randi says:

    Error: $(“#country”).autocomplete is not a function

  112. Vishal Sharma says:

    Thanks …Works perfectly. Very simple.

    Though simple app running on Tomcat 5.x but seems to be very slow.

  113. ravi says:

    This is not working , I m not getting what is q in getdata.jsp

  114. Isuru says:

    It is not working to me, I tried changing getdata.jsp parameter to input name which is country. But still I can’t make it to work.

  115. sharad says:

    Its really……..simple but much effective…..

  116. Mahesh Rathore says:

    “object doesn’t support this property or method” occurs in

    what is the problem, can anyone tell me…

    • Viral Patel says:

      @Mahesh – It seems the autocomplete plugin is not properly included in your html. Check if your local js directory has jquery.autocomplete.js file and that you have included it properly.

  117. sergio says:

    in my browser (firefox) the example does not work…

    changing the order of the includes works!

    First: include jquery
    Then: include autocomplete

    then it works. YMMV

  118. Abhinandan says:

    It is not working for me. Not showing any error too. Please help.

  119. Kateriine says:


    Great, it works here! But not with the HTML5 attribute “autofocus”…

  120. Naveen says:

    thanks for the code its works fine…. but i want to know how to pass extra parameters

    • Viral Patel says:

      @Naveen – You can pass the extra parameters like this:

      $('#country').autocomplete("getdata.jsp", {extraParams: {bar: 4 }} );
      // This will generate url like:
      // getdata.jsp?q=some&bar=4

      Hope that helps.

  121. Rahman says:

    I’m newbie in jQuery,
    autocomplete works fine getting employee names using this code
    /* employeeData.jsp */

    Iterator it=empV.iterator();
    while (it.hasNext()){
    	String myId=(String)it.next();
    	String myName=(String)it.next();

    /* main page */


    But I failed to get the employee id in hidden field, Please what the method I should use
    to get the id in hidden field
    Thanks in advance

    • Viral Patel says:

      @Rahman: I assume you have a requirement where user can select Employee name in autocomplete box and the selected employee’s emp_id should be stored in a hidden field.

      To do this consider following code snippet:

      var data = [ {emp_name:'Employee A', emp_id:'121'}, {emp_name:'Employee B', emp_id: '345'} ];
      $("...").autocomplete(data, {
        formatItem: function(item) {
          return item.emp_name;
      }).result(function(event, item) {

      Here in above code, your jsp generates output in JSon format [ {emp_name:’Employee A’, emp_id:’121′}, {emp_name:’Employee B’, emp_id: ‘345’} ]. Both emp_name and emp_id are present in the json output.

      Also the hidden field id is “hidden_field” whose value we set in result() method.

      Hope this helps you have solves your problem.

      • Rahman says:

        Thank you for your quick reply

        Problem solved when I wrote the piece of code below where empIdTT is a hidden field

        $("#country").result(function(event, data, formatted) {
        		if (data)
  122. m.kishore kumar reddy says:

    thanks for giving this example ….its realy so good try it once

  123. Roopesh says:

    Hi …Thanks alot ..This does work cool …
    Could u please suggest how to generate an action when the user clicks on any suggestion disaplyed ..
    say , For example : In the Example you illustrated i need to direct the user to ‘www.abc.com’ when he/she selects ‘Angola’ .

  124. chlin says:

    thanks a lot

  125. Jigish says:

    Thankss a lot

  126. Dibyendu says:

    good example…

  127. Charul says:

    I am a newbie to jquery. I copied the two file .css and .js file in two new created folders – css and js
    But this program does not work for me…what could be the problem?

  128. John says:

    Hi there, I want to be able to type in as many things as I like, for example: “United Kingdom, Ireland, United States, Afghanistan” I thought this line may hold the key $(‘#country’).autocomplete(“getdata.jsp”, {extraParams: {bar: 4 }} ); but I cant seem to get the second country to pop up or any other. thanks!

  129. John says:

    I thought it would be $(‘#country’).autocomplete(“getdata.jsp”, {multiple: true, multipleSeparator: ‘,’});

  130. Ravi says:

    Thanks Buddy .. Its safe to do >>

  131. sandeep says:

    how can i pass parameter as variable ?

  132. koushik says:

    My code in Jsp :


    code in getdata.jsp:
    String q=request.getParameter(“q”);
    System.out.println(“Value of searchBox:”+q);// for this i’m getting only null value…

    is there any solution…?

  133. avinash kesarla says:


    This really helped me to implement the same in my application.

    But when I am running the same in the tomcat local machine! its working fine! But when deployed into the weblogic(UNIX) Machine, the functionality is not working!

    can you tell me why is it happening so???

  134. Abhimanyu singh says:

    Hi for me it’s not working.from where i can get jquery.custon.js

    • Viral Patel says:

      Hi, Use following JS in your project. You just need Jquery and Jquery Autocomplete plugin JS.
      https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js (jquery-ui.min.js wil have autocomplete plugin)

      • Abhimanyu singh says:

        Hi Thanks,
        This is working fine. I have another problem. when i am doing vertical scrollbar, it’s working find with. i am able to scroll with mouse. but when i am pressing down key , after last value, scrollbar not going down. is there any solution.


        • Deep Shah says:

          Hi Thanks,
          This is working fine. I have another problem. when i am doing vertical scrollbar, it’s working find with. i am able to scroll with mouse. but when i am pressing down key , after last value, scrollbar not going down. is there any solution.


  135. Nagendra Palla says:

    Plzz tell me how can we retrieve data from database (DB2) . plzz give me best solution for this problem it urgent . thanking you in advance .

  136. sam says:

    I am getting exception An error occurred at line: 5 in the jsp file: /getdata.jsp
    DummyDB cannot be resolved to a type
    4: <%
    5: DummyDB db = new DummyDB();
    7: String query = request.getParameter("q");

    • Viral Patel says:

      Check if DummyData.java is included in your source code. Also check if you have changed the package for this class. Following entry must be present in your getdata.jsp file.

      <[email protected] import="net.viralpatel.autocomplete.DummyDB"%>
      • Deepika says:

        I am getting exception An error occurred at line: 5 in the jsp file: /getdata.jsp

        DummyDB cannot be resolved to a type
        4: <%
        5: DummyDB db = new DummyDB();
        7: String query = request.getParameter("q");

        I have checked your reply to this but in my getData.jsp that import is there and also I have not changed the package for the class 'DummyDB' . Any idea what may be the possible cause of this error

      • Deepika says:

        down vote
        It can be resolved as follows:
        This is how I resolved this error (May be useful for some one who wasn’t able to resolve it):

        I was getting the Syntax Error, parameterized types are only if source level is 1.5 & so found this stack overflow link:

        And there I got this solution:

        Go to Project properties.

        Then ‘Java Compiler’ -> Check the box (‘Enable project specific settings’)

        Change the compiler compliance level to ‘5.0’ & click ok.

        Do rebuild. It will be resolved.

        Now it works !!

      • Deepika says:

        Hi Viral,
        I got another problem now. I have used this example as reference in another project. In that project I am providing auto complete in the similar way but when I type an alphabet in text box I am getting the items from my list after some blank lines. I have checked in my database also & there are no empty records in database. Any one having any idea why this issue is coming please let me know.

        Thanks in advance.

  137. Sanjana says:

    Hi viral,
    Thanks for the example..it really helps….I have some more requirement on top this.every country name will have an URL mapped to it.the moment user will select any of the keyword and hit enter/mouse click,it should take user to that page..eg:if user select “America” ,the http://abcd.america.com will open.

    From the java class I am returning the list of bean called,AutoCompleteResultsBean.this bean will have two values,
    2.the URL
    Can you please tell me how can I handle the same with the above code example.

  138. Sanjana says:

    Hi viral,
    If you see the search box in http://www.wallgreens.com,you can see every key word is mapped to an URL..I also ave to implement the same for my app…please help..

  139. misbah says:

    Can you tell me how to add scrollbar to the fetched values.

  140. Girish Panchal says:

    Excillent work ,can you help,how to generate that list from data base ,my table having keywords which i want them to be poppulated when i press any letter

  141. AD says:

    This works like a charm. However it has issues when more than 10 records are returned by the query, and there could be more records…
    For instance say I have data like:
    Test10, Test11, Test12, Test13, Test14, Test15, Test16, Test17, Test18, Test19, Test20
    Let’s say we make a query to fetch the records initially, and that returned the 1st 10 records from
    Test10 to Test19, now when the user types Test20 we should query the backend again, but that is not happening for me…
    I don’t have the choice of returning all the records because there could be millions of records, to I need to trim them down to top ten, but when there is a new character entered, we need to reach back to the backend, for the getData to be called. But that is not getting called when say you type Test2 in above example
    As you are typing Test, it will show top 10 records correctly as Test10…Test19, but as soon as you type 2, it will go blank, and no further calls are made to backend.
    Is there any way to work around this issue?

  142. Devendra Garg says:

    amazing solution…It is working ……..

  143. JJ says:

    I think this is browser specific, not working with Internet Explorer 8

  144. Neelam says:

    Hi viral., how can i use autocomplete with key value pair….your code is working well, i just want to select key from div and their value is displayed in textbox…..how it possible?

  145. PAM says:

    A simple and very nice tutorial. Thanks for posting it!

  146. Deep Shah says:

    Hi Viral,
    You did the great work. I integrated it successfully. But still i want more functionality with this auto complete is that i only initially want 3 items in auto complete and when there will be more than 3 items at that time auto scroll should be come and when user key down in that auto scroll box at that time scroll down should be work automatically.

    Thanks in advance

  147. bhargavi says:

    this is working fine for static data,…
    but how for dynamic ….. i mean i need to populate names in auto complete textbox and values should be retrieved from database…… how does it work?

  148. nitin says:

    It works, thanks,
    But how to change background color? of the form where country is written?

    • Viral Patel says:

      If you want to change background color of country textbox then just apply this css.

      #country {
  149. agrasso says:

    Hello Viral,

    Thank you for your example, I did the implementation and works very fine with JSPand mySql Server. but I have a question :

    Sometimes I have more than 30 elements and I want to show a vertical scroll bar and limit the size of the list, for example : 15 elements.

    I don’t know if you can help me.

    I’m trying by myself.

    Thank you.

    Have a nice day.

  150. Mubarak says:

    sir i am new in java spring
    will you gave me example where i am using table name trainer which have many field like name, email,phone etc
    then tell me what is the code to make auto complete the trainer name in text field from mysql database in the spring mvc trhu hibernte

    and if you give a complete code then i m very thank full to you

    plz reply
    & thanks in advance

  151. Kenneth says:

    Really nice works like a charm. Thank you

  152. mallii says:

    this is
    very good example

    please give example on struts2 hibernate

  153. Sachin says:

    Hi Viral,

    I am using the above example with Spring Mvc and trying to load getdata.jsp but it is not showing any value inside index.jsp’s textbox. I am passing value from spring controller to jsp in a request object as an attribute. If u help me in this that wwould be really nice.

  154. jatin says:

    Where from this “q” comes? As there is no parameter whose name is q in index.jsp
    String query = request.getParameter(“q”);

    • ezfzgf says:
      As said Jatin,
       does anybody know where that
       String query = request.getParameter(“q”);
      comes from ??
       if you remove or change the “q” in something else, it simply doesnt work anymore !!!
       That is driving me insane…

      look at jquery.autocomplete.js, line 337:

      function makeUrl(q) {
      		var url = options.url + "?q=" + encodeURI(q);
      		for (var i in options.extraParams) {
      			url += "&" + i + "=" + encodeURI(options.extraParams[i]);
      		return url;
      • x person says:

        really nice example understand easily for freshers:)

  155. shiv says:

    Hi… I am getting the following error… what i’ii do…
    HTTP Status 500 –


    type Exception report


    description The server encountered an internal error () that prevented it from fulfilling this request.


    org.apache.jasper.JasperException: An exception occurred processing JSP page /getdata.jsp at line 10

    8: String query = request.getParameter(“q”);
    10: List countries = db.getData(query);
    12: Iterator iterator = countries.iterator();
    13: while(iterator.hasNext()) {


    root cause


  156. Thomas says:

    As said Jatin,
    does anybody know where that
    String query = request.getParameter(“q”);
    comes from ??
    if you remove or change the “q” in something else, it simply doesnt work anymore !!!
    That is driving me insane…

    • Deepika says:

      Hi Thomas,
      If you use firebug to check the url which is generated after you enter the alphabet in text box, you can see that at the end of that url parameter is being added. Like if you type ‘w’ then at the end of generated url you get ?q=”w”. So, if we do request.getParameter(“q”) on getData.jsp then you get the alphabet which is entered on index.jsp on getData.jsp. Hope it helps.

  157. samydurai says:

    above example is very nice and super.

  158. Ashwin kumar says:

    hi viral. i want help form you if u wish to do.i m new to java. i want to view sub ordinate hierarchy in tree structure in jsp while i was using common table expression in java it give error. however if you any example in related to this can u send me [email protected] …Thanks in advance and hoping some good suggestion related same………it help me to complete my intern

    Declare @LoggedInUserID int = 2;
    With User_Cte as
    	Select UserID, UserName, DesigID, ReportingTo   
    	from Users 
    	where UserID = @LoggedInUserID
    	Union ALL
    	Select t2.UserID, t2.UserName, t2.DesigID, t2.ReportingTo   
    	from Users t2
    	Inner join User_Cte as uc on uc.UserID = t2.ReportingTo   

    Is there any specification is available to get hierachy or Ranking to display in tree structure in jsp.
    Appreciate your help and also your blog is very useful to me.

  159. Basappayya says:

    Thanks a lot, Very nice example.

  160. Vishwnath M Patil says:

    super example……..

  161. rahul srivastava says:

    hi viral sir, it was really a workable and good example, but if you dont mind can u explain its flow, i mean how values are coming inside textbox and how we are able to select them.Is it possible due to the jquery APIs??
    also why we are getting “q” as a parameter here?Kindly explain
    rest it is all ok i could meet my objective……..

  162. Sonia says:

    Hi Viral,
    First of all this is really a fantastic example. I have a question and its troubling a lot. the question is I am trying to use a method along with .autocomplete forexample select: function()
    i.e. $(“#country”).autocomplete(“getdata.jsp”, {select: function(){alert(“hello”);}); I tried a lot but failed, please if you can tell me how can I use another method in this example would be great. My requirement is select multiple values in a text box. For example india, australia, austria


  163. Rahul Srivastava says:

    Hello sir, it is working fine but its working slow and some time it does not take the values and can we improve its UI…………….

  164. Wicharn says:

    Thanks a lot. This is a very good example. Could you please give me another example on how to add the database implementation as you mentioned?

  165. Pavan says:

    I wanted to this script in the external javascript file. But it is not working .
    Please help me out on this


  166. Amir says:

    Good one but according to Oracle need to change the StringTokenizer part to split.
    “StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.”

  167. Sudhakar says:

    All topics are really wonderful , Thanks for your valuable post!!

  168. Deepika says:

    Hi Viral,
    I got one problem now. I have used this example as reference in another project. In that project I am providing auto complete in the similar way but when I type an alphabet in text box I am getting the items from my list after some blank lines. I have checked in my database also & there are no empty records in database. Any one having any idea why this issue is coming please let me know.

    Thanks in advance.

  169. Omkar Deshmukh says:

    hi team,

    i am requesting one parameter through request.getParameter(); in my servlet from on jsp. what will happend if i dont pass values to this parameter from that jsp.

    will it cause Bad Request exception?

    kindly give me the solution for this if yes.

  170. Anonymous says:

    Hi VP,

    Nice Example and working fine. But Could you please explain how request.getParameter(“q”); gets populated?

  171. anit says:

    can someone help me out
    i am getting below meessage when i try to run above example


    type Status report

    message /AutocompleteExample/

    description The requested resource (/AutocompleteExample/) is not available.

  172. Shakti Ranjan says:

    hello sir,

    this code is working fine,
    this website helped me and my friends most.


  173. Navs says:

    Thansk Virat!! nice example

  174. Blasko says:

    Pls little help, I don’t know how to get this work with cyrillic letters… Thanks in advance

  175. viju says:

    Thanks for the tutorial. I was looking for some source which will get my work done really fast. After reading this tutorial, it appeared the parameter “q” seems to be haunting everyone. As suggested by Deepika, it is passed as a parameter by getData.jsp (host/app/getData.jsp?q=”in” ). It contains the letters you type in the country box.
    The “q” can be traced in jquery.autocomplete.js in the function requestData(q).

    function requestData(q) {
    		if (!options.matchCase) q = q.toLowerCase();
    		var data = options.cacheLength ? loadFromCache(q) : null; 
                   : :

    JQuery uses this to pass the content of the selector $(#country) to autocomplete() ‘s requestData() function and then it is passed to the getData.jsp which is used above in the code. Hope this helps everyone who have been wondering where q comes from. Cheers! :).

  176. Poonam says:

    Hey unfortunately it’s not working in my case :(..suggestions are not being shown after typing letter(s)..wat can b d possible reason(s)??

    • jayant says:

      Thanks Viral, Its working for me…

      @Poonam .. r u using db for fetching values?

  177. pathak nisarg says:

    Hey unfortunately it’s not working in my case .suggestions are not being shown after typing letter(s)..what can b d possible reason?

  178. Waseem Akram says:

    Hi , i m trying to generate autocomplete feature for dynamically generated text boxes
    can u please help me out in attaining this feature

    thanks in advance

  179. parth says:

    thank you very much. Nice work!

  180. Shruthi says:

    Hey great tutorial !!!! Keep going !

  181. Arun says:

    Hi sir your code is working fine.. But i have a problem in date picker..
    In 1.3.2 js date picker not working but if i attach 1.9.2 js ,date picker is working fine but auto complete is not working.. Please help me sir….

  182. Raghu says:

    Hi Viral,

    Can you please help me to integrate autocomplete feature with h:selectonemenu ?

    <h:selectOneMenu id=”location_id” value=”#{DataUpdateBean.Location}”>
    <f:selectItem itemValue=”” itemLabel=”” />
    <f:selectItems value=”#{DataUpdateBean.LocationList}” />


  183. Ozan says:

    Hi Viral great exampe:

    How can I set min character before bring the suggestions ?

    Thank you !

    • Anny says:

      Hi..I am getting one problem for the autocomplete example.I have added database connection in DummyDB.java file.In tomcat its working fine,but in JBoss its throwing Null Pointer Exception. I am using struts 1.2 framework and SQL server 2005.Please help me,its urgent..Thanks in advance.

  184. saurabh says:

    Hi , How we can use jquery.autocomplete.js library in angularjs ? could you give any example

  185. Wally says:

    Looks nice and everything is working for me… The only question I have is: Is there any way not to reference http://www.google.com/jsapi? I am not allowed use out side references.

    Thanks in advance…

  186. Kirti Batra says:

    Your Code helps alot !

  187. Priyanka says:

    Hi VIral,

    Very clean tutorial. I was looking for just the same and it worked smooth.Thanks a lot.
    When i tried the same script fr numbers, it is not working (eg. job Ids)
    Please tell me how to make it work for numbers.
    Thanks in advance.

  188. Priyanka says:

    Sorry Viral,
    Its working for numbers as well.
    Thansk a lot.

  189. sadhvi says:

    Hi thank you for such a wonderful tutorial,
    I have a question i am creating Timesheet app using JSP and servlets. And i am trying to add all week 1 values and place them in totalweek1. i am using jquery but for some reason i am not able to acheive the reuslt

    PLease help

  190. Manish Aryan says:

    very nice code must go for it….

  191. Kunal says:

    Hello Viral

    It’s amezing work but how we can fatch backhand list


    auto_ad_tag_options = new ArrayList();
    auto_ad_tag_options.add(1, “Kunal”);
    auto_ad_tag_options.add(2, “Jitesh”);

    In xhtml page.

Leave a Reply

Your email address will not be published. Required fields are marked *