Newsletter

Example: Get Autocomplete Feature In Java/Jsp With jQuery API

jQuery » on Sep 9, 2012 { 58 Comments } By Sivateja

Hi friends, let us see how to get autocomplete effect in normal java/jsp applications, with the help of jQuery. I hope every body knows the importance of using autocomplete feature in java/.net or some other technologies.ย ย  Am going to use jQuery API in order to get this effect into normal jsp to make our life little easier ๐Ÿ™‚ , let us start….

Required Files:

  • index.jsp
  • list.jsp
  • jquery.autocomplete.js
  • jquery-1.4.2.min.js
  • style.css

Web application Directory Structure:

te

Note:ย  File i used in css,images directories are just for giving little graphical touch ๐Ÿ™‚ if want you can remove them.

index.jsp:

<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<script type="text/javascript" src="JS/jquery-1.4.2.min.js"></script>
<script src="JS/jquery.autocomplete.js"></script>
<script>
jQuery(function(){
$("#country").autocomplete("list.jsp");
});
</script>

</head>
<body>
<br><br><center>
<font face="verdana" size="2">
<font size="4">Java(jsp)/jQuery Autocompleter Example ::: <font color="#809e02">Java4s.com</font></font>
<br><br><br><br>

Select Countryย ย  :
<input type="text" id="country" name="country"/>

</font>
</body>
</html>

List.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>
<%@page import="java.util.*"%>

   <%
   try{
     String s[]=null;

     Class.forName("oracle.jdbc.driver.OracleDriver");
     Connection con =DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system","admin");
     Statement st=con.createStatement();
     ResultSet rs = st.executeQuery("select * from countries");

       List li = new ArrayList();

       while(rs.next())
       {
           li.add(rs.getString(1));
       }

       String[] str = new String[li.size()];
       Iterator it = li.iterator();

       int i = 0;
       while(it.hasNext())
       {
           String p = (String)it.next();
           str[i] = p;
           i++;
       }

    //jQuery related start
       String query = (String)request.getParameter("q");

       int cnt=1;
       for(int j=0;j<str.length;j++)
       {
           if(str[j].toUpperCase().startsWith(query.toUpperCase()))
           {
              out.print(str[j]+"\n");
              if(cnt>=5)// 5=How many results have to show while we are typing(auto suggestions)
              break;
              cnt++;
            }
       }
    //jQuery related end

rs.close();
st.close();
con.close();

}
catch(Exception e){
e.printStackTrace();
}

//www.java4s.com
%>

style.css

.ac_results {
	padding: 0px;
	border: 1px solid #84a10b;
	background-color: #84a10b;
	overflow: hidden;
}
.ac_results ul {
	width: 100%;
	list-style-position: outside;
	list-style: none;
	padding: 0;
	margin: 0;
}
.ac_results li {
	margin: 0px;
	padding: 2px 5px;
	cursor: default;
	display: block;
	color: #fff;
	font-family:verdana;
	/*
	if width will be 100% horizontal scrollbar will apear
	when scroll mode will be used
	*/
	/*width: 100%;*/
	font-size: 12px;
	/*
	it is very important, if line-height not setted or setted
	in relative units scroll will be broken in firefox
	*/
	line-height: 16px;
	overflow: hidden;
}
.ac_loading {
	background: white url('../images/indicator.gif') right center no-repeat;
}
.ac_odd {
	background-color: #84a10b;
	color: #ffffff;
}
.ac_over {
	background-color: #5a6b13;
	color: #ffffff;
}
.input_text{
	font-family:Arial, Helvetica, sans-serif;
	font-size:12px;
	border:1px solid #84a10b;
	padding:2px;
	width:150px;
	color:#000;
	background:white url(../images/search.png) no-repeat 3px 2px;
	padding-left:17px;
}

Output:

Explanation:

See in list.jsp line no.33 you may get one doubt, what is that ‘q‘ right ? in fact we are not sending any parameter with name ‘q’ from the input.jsp but for every keyup in the text box (in index.jsp) jquery will sends each character to the list.jsp in the form of ‘q’ and compares with the values in that list, i mean ‘q’ is the default parameter using by jQuery API.

How to send extra parameters along with that q:

$(‘#country’).autocomplete(“list.jsp”, {extraParams: {state: California }} );

This will generates the internal URL like

……./getdata.jsp?q=ourChar&state=California

 

Output Video Format:

โ€‹ โ€‹โ€‹

You Might Also Like

  ::. About the Author .::

Java4s_Author
Sivateja Kandula - Java/J2EE Full Stack Developer
Founder of Java4s - Get It Yourself, A popular Java/J2EE Programming Blog, Love Java and UI frameworks.
You can sign-up for the Email Newsletter for your daily dose of Java tutorials.

Comments

58 Responses to “Example: Get Autocomplete Feature In Java/Jsp With jQuery API”
  1. ASD says:

    Good One Java4s team.nice explanation..:)

  2. Java4s says:

    @ASD

    Thank you ๐Ÿ™‚

  3. Pavan says:

    good example…sir,is their any jquery plugin for automatic session end of an user and logging out if the user is idle for some time…eg banking application…

  4. Java4s says:

    @Pavan

    Yeah we can use ‘jQuery Idle Timeout‘ concept, but i don’t encourage this way as being in session is very important for any application, if we use jQuery for sessions its little risky as jQuery depends on browsers some times.

    So always better choice is considering the underlying(in what technology we did the particular application) technology only.

  5. Ramkumar says:

    What if i want autocomplete from multiple table from a database

  6. srinivas says:

    Hai sir…………my question is…i done as same in ur page….but it’s not able to autocomplete the testbox…i created a table “countries” in database also..i added a jar file also…please suggest me to autocomplete..
    THANKS IN ADVANCE

  7. Srinu says:

    Hi, can you please explain me what is the content in jquery.autocomplete.js file and navigation from jsp page to jquery.

  8. Java4s says:

    @Srinu

    It is predefined API file, we no need to worry about that, just download and use it ๐Ÿ™‚

  9. Raaj says:

    I am using same as written here in the code , but m not getting the data..even i am printing the ‘q’ in the list.jsp ,,,,, that file also not calling even…….
    All and all in this ‘list.jsp’ is not calling ……m having that list.jsp in other location so m passing the path there,,,,,
    “jsp/masters/list.jsp” ……..please help me for this.

  10. vikram says:

    Sir thanks alot…. Fan fan fan….. ๐Ÿ™‚

  11. vijay says:

    where do i get jquery.autocomplete.js and jquery-1.4.1.min.js required files

  12. Good Example, i got the result but when i am searching something, that is not in the list it showing many nullpointer exceptions, give solutions

  13. Praveen says:

    I followed your tutorial but the autocomplete showed “No Search Results” although i can see the results in the response sent by server in the developer tools.. What can be the issue?

    I also posted the question on stackoverflow – http://stackoverflow.com/q/16207918/1208469

  14. Afzal says:

    Thanks for this great example.. can you please help me in this case.
    In the same example i have a text box in Display.jsp and i want to send the parameter of the same text box to fetchData.java so that i can use it in sql query where condition

  15. Siva says:

    It’s ok. but How to create auto complete search for multiple tables data…

  16. alaa says:

    it good example
    but i try to with Arabic data it not work

  17. sanath says:

    this is excellent work……

  18. prasad says:

    nice example, its workingggggg.

  19. VenuGopal says:

    Hi Java4s,,,

    above example superb for single instance..and how to implements for mulltiple input instance…
    plz solution its emergency…
    thanks,

  20. kautuk says:

    thanq for the example .but as i am java learner i am not able to find Jquery so can u please send path or Jquery

    thank you once again

  21. lakshmi says:

    Hi, Thanks For This Great Example. can you please help for some issue is if i place this auto complete text box in div. results are moving along with div because that div has overflow: auto. but i don’t want that. can you please give me solution for this.

  22. Mahesh says:

    could update JSP and Webservices I am eagerly waiting for those topics
    please do it as soon as possible…

  23. Tharun says:

    thanks for the example. Its really good and understandable.

  24. I am using same as written here in the code , but m not getting the data..I created table in database and i attach all jars but i am not getting it.pls give some suggestions
    Thanks in advance

  25. Erick Matla says:

    Excellent!!!

  26. pavithra says:

    Really good site for beginners like me…… step by step explanations…I would suggest this site for my colleagues and friends
    ๐Ÿ™‚

  27. Rajesh says:

    how to select intenseness item in auto complete items ? Can you explain briefly ?

  28. kausy says:

    Hi,
    Marvelous efforts man.Hats off.That was nice script .It has reduced my efforts.Only thing here I didn’t get is what do I need to do if I want to trigger this autocomplete function on getting 3 characters in input box.Where do I need to change in autocomplete script??It will be great if I get response .

    THanks in advance

  29. subhransu says:

    In my case. It is not working. I am using net beans.Changed the searchcontroller to controller in autocompleter.js only.

  30. Veerendranag says:

    Good Example for Begineers and Very easy to understand

  31. Chinna says:

    Good example..

  32. raj says:

    good example thanks.Implemented successfully.But If i select all results from table i want to limit results in dropdown to 5 so change following in autocomplete: function(urlOrData, options) in autocomplete.js
    max: options && !options.scroll ? 10 : 150
    to
    max: options && !options.scroll ? 1 : 5
    now it is showing only 5 suggestion.is it right way to limit result in autocomplete or not?pls help me its urgent.

  33. raj says:

    if table consists of thousands or lacs of records,then it take time to load records or it get work?becoz we write query select empname from table;it consider all records of empname column.pls help me.Thank u for help.

  34. Anu says:

    I want to continue this autoComplete effect for sentences. Where should I need to do the modifications? Do I need to change the JQuery?

  35. Nimish says:

    How to insert this code in my project.
    it is not working/i am not able to integrate this code in my project.
    pls suggest me how to integrate.?

  36. munish says:

    i have 4 textbox on html page i would like to fill other 3 textbox on behalf of one like on enter bank name it related value display in textbox without click on submit button

  37. Neha says:

    Hi,
    How to integrate this in struts2 application.
    Any help will be appreciated.

    Thanks in advance.

  38. Sagar says:

    Hi,

    How do i get the below required files?
    jquery.autocomplete.js
    jquery-1.4.2.min.js

  39. Vinu says:

    Great work. Sir i am using the same code. and i want to pick the data that i clicked from the auto suggested list, so that i can use the same data in other sql query. How it is possible?

  40. prog says:

    jquery autocomplete is passing additional parameters like limit and timestamp how to pass only q parameter

  41. kumAR says:

    Thanks to sharing ur knowledge with us….

  42. mohan says:

    This is very nice script.

  43. Rohit says:

    I have a dropdownlist of database column.If i select city instad of country it shows both city and country.
    How i do it correct?

  44. Mahesh says:

    I am able to run the project after downloading the same, but it is not working in my project and giving

    Error: TypeError: $(…).autocomplete is not a function

  45. Avinash says:

    Thanks for sharing
    But how to select a particular name in the names given below and store it in a variable so that i can give an alert message like “This is selected”

  46. RamChithra says:

    This is very nice,but how to get selected textbox value,for example
    Customer Name :ram
    Selected value:ram

  47. Prateek says:

    sir,
    jquery.autocomplete.js is not available even at jquery.com site..

    can you please provide any substitute to this script file.

    even by attaching it online.
    (http://code.jquery.com/jquery.autocomplete.js)

    it shows PAGE 404 Not Found

  48. rishabh says:

    sir its working in my application but i dont want cache facilty how can i remove it

  49. Hemanth Kumar says:

    Hi

    I tried this solution. from list.jsp, I am getting the response of the filtered matches but the results are not getting displayed in the main jsp page. What I mean is drop down is not displaying. I tried to increase the z-index also but that also is not working. Can you please help me to solve this issue please

    • stelina says:

      there is a tag </center> missing .That fixed it for me. You can download the files needed by clicking the download button!!

  50. Nitin Gandge says:

    Nice Example…
    Can you please tell me how to get selected value in this example and display in paragraph or in other textbox

  51. hitzone says:

    how to select first element of list.jsp on blur.actually i am getting first element but after when i select it give me first element rather than giving the selected one.

    <script>
    jQuery(function(){
    var a =$("#country").autocomplete("list.jsp");
    alert("fgfdg"+a);

    var select = false;

    $("#country").autocomplete({
    // source: a,
    autoFocus: true,
    selectFirst: true,
    open: function(event, ui) { if(select) select=false; },
    select: function(event, ui) { select=true; }
    }).blur(function(){
    if(!select)
    {
    $("#country").val($('body > div > ul>li:first-child').text());
    //$("#country").val("fsdfsd");
    }
    });

    });
    </script>

  52. malesh says:

    I want pass more that 2 values in text box separated by coma(,) like gmail compose.

  53. Subbu says:

    You really saved my day ๐Ÿ™‚

  54. saniya says:

    Sir how can we implement this autocomplete feature with hibernate because you use jdbc so how can you please explain with hibernate

  55. krushi says:

    Hi,

    How do i get the below required files?
    jquery.autocomplete.js
    jquery-1.4.2.min.js

Name*
Mail*
Website



By posting your answer, you agree to our comments policy.
Most Recent Posts from Top Categories
Spring Boot Hibernate Spring
Contact | About Us | Privacy Policy | Advertise With Us

© 2010 - 2024 Java4s - Get It Yourself.
The content is copyrighted to Sivateja Kandula and may not be reproduced on other websites.