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;
}
}
Code language: Java (java)
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. <!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 type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></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"/>
<script>
$("#country").autocomplete("getdata.jsp");
</script>
</body>
</html>
Code language: HTML, XML (xml)
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");
Code language: JavaScript (javascript)
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);
}
%>
Code language: Java (java)
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
Code language: CSS (css)
Execute the code in eclipse and you will get the desired output: Java URL Encoder/Decoder Example - In this tutorial we will see how to URL encode/decode…
Show Multiple Examples in OpenAPI - OpenAPI (aka Swagger) Specifications has become a defecto standard…
Local WordPress using Docker - Running a local WordPress development environment is crucial for testing…
1. JWT Token Overview JSON Web Token (JWT) is an open standard defines a compact…
GraphQL Subscription provides a great way of building real-time API. In this tutorial we will…
1. Overview Spring Boot Webflux DynamoDB Integration tests - In this tutorial we will see…
View Comments
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.
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