Newsletter |
Example: Get Autocomplete Feature In Java/Jsp With jQuery API
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 .:: | ||
Good One Java4s team.nice explanation..:)
@ASD
Thank you ๐
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…
@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.
What if i want autocomplete from multiple table from a database
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
Hi, can you please explain me what is the content in jquery.autocomplete.js file and navigation from jsp page to jquery.
@Srinu
It is predefined API file, we no need to worry about that, just download and use it ๐
good work
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.
Sir thanks alot…. Fan fan fan….. ๐
where do i get jquery.autocomplete.js and jquery-1.4.1.min.js required files
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
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
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
It’s ok. but How to create auto complete search for multiple tables data…
it good example
but i try to with Arabic data it not work
this is excellent work……
nice example, its workingggggg.
Hi Java4s,,,
above example superb for single instance..and how to implements for mulltiple input instance…
plz solution its emergency…
thanks,
—
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
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.
could update JSP and Webservices I am eagerly waiting for those topics
please do it as soon as possible…
thanks for the example. Its really good and understandable.
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
Excellent!!!
Really good site for beginners like me…… step by step explanations…I would suggest this site for my colleagues and friends
๐
how to select intenseness item in auto complete items ? Can you explain briefly ?
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
In my case. It is not working. I am using net beans.Changed the searchcontroller to controller in autocompleter.js only.
Good Example for Begineers and Very easy to understand
Good example..
Worked like charm:)
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.
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.
I want to continue this autoComplete effect for sentences. Where should I need to do the modifications? Do I need to change the JQuery?
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.?
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
Hi,
How to integrate this in struts2 application.
Any help will be appreciated.
Thanks in advance.
Hi,
How do i get the below required files?
jquery.autocomplete.js
jquery-1.4.2.min.js
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?
jquery autocomplete is passing additional parameters like limit and timestamp how to pass only q parameter
Thanks to sharing ur knowledge with us….
This is very nice script.
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?
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
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”
This is very nice,but how to get selected textbox value,for example
Customer Name :ram
Selected value:ram
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
sir its working in my application but i dont want cache facilty how can i remove it
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
there is a tag </center> missing .That fixed it for me. You can download the files needed by clicking the download button!!
Nice Example…
Can you please tell me how to get selected value in this example and display in paragraph or in other textbox
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>
I want pass more that 2 values in text box separated by coma(,) like gmail compose.
You really saved my day ๐
Sir how can we implement this autocomplete feature with hibernate because you use jdbc so how can you please explain with hibernate
Hi,
How do i get the below required files?
jquery.autocomplete.js
jquery-1.4.2.min.js