I really enjoy jQuery. But finding the right UI widget can be a daunting task.
Autocomplete is one of those widgets.
I decided to share an asynchronous example on how to use the jQuery Autocomplete plugin with Stripes.
Here’s an example output:

First of all you need to download jQuery (1.2.6) and the last jQuery UI (1.6.rc2).
Then write a simple action bean:
public class AutocompleteActionBean implements ActionBean {
private ActionBeanContext context;
private String q;
private static final List<string> cities = Arrays.asList(
"Aberdeen", "Ada", ...);
// Getters and Setters
/**
* Forwards the user to the example page.
*
* @return forward to the jsp
*/
@DefaultHandler
public Resolution main() {
return new ForwardResolution("/WEB-INF/autocomplete.jsp");
}
/**
* Returns the city's list for the autocomplete drop down.
*
* @return a StreamingResolution with the city's list
*/
public Resolution autocomplete() {
StringBuilder results = new StringBuilder();
if (q != null) {
for (String city : cities) {
if (city.indexOf(q) != -1) {
results.append(city).append("\n");
}
}
}
return new StreamingResolution("text/plain", results.toString());
}
}
The jQuery Autocomplete plugin needs the newline character (“\n“) to separate autocomplete options.
Next, write your JSP, and import the needed CSS and JavaScript files from jQuery and jQuery UI.
<%@ include file="../includes/taglibs.jsp"%>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title><fmt:message key="autocomplete.example.title" /></title>
<link type="text/css" rel="stylesheet" href="/styles/ui.autocomplete.css" />
<script type="text/javascript" src="/scripts/jquery-1.2.6.min.js"></script>
<script type="text/javascript" src="/scripts/ui.core.min.js"></script>
<script type="text/javascript" src="/scripts/ui.autocomplete.min.js"></script>
<script type="text/javascript" src="/scripts/script.js"></script>
</head>
<body>
<fieldset>
<legend><fmt:message key="autocomplete.example.title" /></legend>
<s:form beanclass="com.samaxes.autocomplete.presentation.action.AutocompleteActionBean" focus="city">
<p><s:label for="city" /></p>
<p><s:text id="city" name="city" /></p>
</s:form>
</fieldset>
</body>
</html>
Finally, in your script file, bind the autocomplete event to the input element, and point the URL to the autocomplete handler of the AutocompleteActionBean action bean.
$(document).ready(function() {
$('#city').autocomplete({
url: '/Autocomplete.action?autocomplete=',
minChars: 1,
max: 10,
width: 150,
scroll: false
});
})
For the complete list of options for this plugin go http://docs.jquery.com/UI/Autocomplete/autocomplete and click on the “Options” tab.
This is turning into one of my favorite blogs, awesome content samaxes… jQuery is still totally foreign to me, thanks.
Hi,
I tried this example, is not working. could you please share working script/war file
thanks in advance
Hey Nila,
At the end of the article you have a “Get this example source code!” link pointing to a complete working example.
Thanks Sam. I appreciate your help. I need another favour from you. How to set the width of the drop down. I tried all the option, size remains the same.
thanks in advance,
You can change the width by changing the
widthoption of the plugin.$(document).ready(function() { $('#city').autocomplete({ url: '/Autocomplete.action?autocomplete=', minChars: 1, max: 10, width: 150, scroll: false }); })thanks Sam for the quick response. this helped me a lot.
hello sir,
i want urgent help from u. i am using three drop down boxes and a text field in jsp. the first drop down fetches the district values from sql table and the second drop down box fetches the area values and the third fetches airport values i want all the three will autocomplete and autosuggest please help me thanks in advance
The easiest way to achieve that is to create three handlers in your ActionBean and three AJAX calls in you JavaScript. One for each drop down.
Hello Sam,
I have a question, i have two text box
calls auto_text1
calls auto_text2
autocomplete of text2 is depend on text1, how to get the values of text1 in aut_text2.
thanks in advance,
Sincerely yours,
raghu n m
You can pass the value of the
auto_text1as a parameter to the server and filter the elements to return to theauto_text2. Example:$(document).ready(function() { $('#auto_text2').autocomplete({ url: '/Autocomplete.action?autocomplete=&text1=' + $('#auto_text1').val(), minChars: 1, max: 10, width: 150, scroll: false }); })thanks Sam.
my apologies this how the code looks like,
jsp code
js code
$(document).ready(function() { $('#text1').autocomplete({ url: '/xref/Search.action?autocomplete_text1=', minChars: 1, max: 10, size: 40, scroll: true }); }) $(document).ready(function() { $('#text2').autocomplete({ url: '/xref/Search.action?autocomplete_text2=&text1='+ $('#text1').val(), minChars: 1, max: 10, size: 40, scroll: true }); })in server side
public Resolution autocomplete_text2() { System.out.println(text1); StringBuilder results = new StringBuilder(); if (q != null) { for (String name : lists) { if (name.indexOf(q) != -1) { results.append(name).append("\n"); } } } return new StreamingResolution("text/plain", results.toString()); }out put
when i try to print text1 in server side i recieved ‘null’ for
url: ‘/xref/Search.action?autocomplete_text2=&text1=’+ $(‘#text1′).val(),
and ‘undefined’ when i use
url: ‘/xref/Search.action?autocomplete_text2=&text1=’+ $(‘#autocomplete_text1′).val()
You cannot use the url
'/xref/Search.action?autocomplete_text2=&text1='+ $('#autocomplete_text1').val()since you don’t have any HTML element with the idautocomplete_text1.The url
'/xref/Search.action?autocomplete_text2=&text1='+ $('#text1').val()should work fine if you have the setter for the propertytext1in your ActionBean. Pay attention to not use&instead of&in your JavaScript.thanks Sam. Still it is still printing null. Do you have any working example.
thanks in advance,
nila
Sorry Nila, but I don’t have any example with dependent combo boxes.
oh!!! thanks any way. i will try , if it works i will post the code.
hello Sam
if i use $(‘#text1′).val() it ruturns null , but it returns [object, object] if i use $(‘#text1′).
is this something we can fix in jquery.
any thoughts
Sincerely yours,
raghu nm
Try debugging it with Firebug:
console.log($('#text1'));Hello Sam,
facing some problem while using component. when click on the drop down list to select item from it, it is submitting action form.
Please give some tips to avoid this action.
thanks in advance,
nila
Hi Sam,
Do you a working jquery autocomplete based on Spring MVC. Can u suggest how to get it done.
–Irshad.
Sorry Irshad, I do not work with Spring MVC.
hi Samuel. I make a project in NetBeans and put your code and files in it. It works. At least I can see the page like in the very beginning of this page.
But after project is started TomCat sends the next message
INFO: Could not locate property of name [city] on ActionBean.net.sourceforge.stripes.util.bean.NoSuchPropertyException: Bean class com.samaxes.autocomplete.presentation.action.AutocompleteActionBean does not contain a property called ‘city’. As a result the following expression could not be evaluated: city
I checked all code and config files for two times, but can not fix the problem. There is not really property ‘city’ in ‘AutocompleteActionBean’
what’s wrong?
I’m using NetBeans 6.5, jdk 1.6, tomcat6, stripes 1.5.1
Excuse me one more time! I have got one more strange message:
DEBUG DefaultMultipartWrapperFactory:183 – DefaultMultipartWrapperFactory not using net.sourceforge.stripes.controller.multipart.CommonsMultipartWrapper because it failed to load. This likely means the supporting file upload library is not present on the classpath.
It seems like there are not all needed jars in classpass. Now I have in classpass the following libraries:
common-logging
cos
stripes
log4j
jstl
Shall I have some more?
Thanks in advanse!
ICQ 327 970 467
Hi chum,
Your two questions are related to Stripes. I encourage you to post Stripes questions to the Stripes Users mailing list: http://news.gmane.org/gmane.comp.java.stripes.user.
This is an info message, not an error. It’s something that happens frequently in Stripes. But I really don’t know the reason for this to happen.
Relating to the Stripes
DefaultMultipartWrapperFactory, please read Stripes File Uploads: http://www.stripesframework.org/display/stripes/File+Uploads.You are probable missing an initialization parameter in the Stripes Filter or a needed library for file uploads.
Hi Sam, hi everybody!
I have the last question concerning the sample. I know exactly that DEBUG message I recieved was generated by Stripes:
DEBUG http-8084-3 controller.UrlBindingFactory:debug:183 – No URL binding matches /WEB-INF/autocomplete.jsp
I need this sample work very much, so I ask everybody what is wrong? It seems the problem is in configuration: web.xml or something else.
Would you be so kind to send me (if you have) the working sample .war or Eclipse or Netbeans project?
chumansky@gmail.com
thanks in advance
Hi chum,
You can’t directly access
jspfiles under theWEB-INFfolder.This is forbidden by the servlet specification.
To have this example working, unzip the source code file and build the project by running the maven goal mvn package inside the folder where you have unzipped the source code.
Then copy the
warfile insidetargetfolder to your server.It will deploy under the
/context path (e.g.http://localhost:8080/).i’ve got some error on these line:
import net.sourceforge.stripes.action.ActionBean;
…
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.StreamingResolution;
what should i do?
opss, sorry..
i didn’t notice it was STRIPES lib
how can i do selectbox item selection change trigger autocomplete..thanks
I’m sorry, I didn’t understand your question.
I got the example to work. It’s great!
But, I have one question: Who is calling setQ() in the AutocompleteActionBean? There is nothing in the script.js or autocomplete.jsp that actually calls this method.
S/T
jQuery Autocomplete plugin adds a
qparameter to your query string.Since a property with the same name is defined in the ActionBean its setter will be called.
Example of a XMLHttpRequest URL:
http://localhost:8080/Autocomplete.action?autocomplete=&q=a&limit=10×tamp=1250114891141
Samuel — Great post. Thanks. VERY helpful!
Hi Samuel. Can you please verify if the above code works for Chinese characters? I am facing some issues with Chinese chars. If i define the unicode equivalent for chinese chars in my data string i.e.
private static final List cities = 1.5.0/docs/api/java/util/Arrays.html”>Arrays.asList(
“Aberdeen”, “Ada”, “\u8FD4\u56DE\u8FD4\u56DE”, “\u8FD4\u56DE\u8FD4″, …);
And then type the chinese chars in the text box, then this code wont work.
Can you please help me in the same?
Hi Samuel,
I am getting following issue, Could please give me suggestion.
INFO: Could not locate property of name [city] on ActionBean.net.sourceforge.stripes.util.bean.NoSuchPropertyException: Bean class com.samaxes.autocomplete.presentation.action.AutocompleteActionBean does not contain a property called ‘city’. As a result the following expression could not be evaluated: city
Would you be so kind to send me (if you have) the working sample .war
Hi Vishnu,
This is a recurring question as you may notice from earlier comments.
The message you got is not an error, it’s a Stripes info message.
It’s something that happens frequently with Stripes and may already have been fixed in latest versions.
@nila you can use
select: function instead to pass selected value of your autocompletedTExtBox_1 to autocompletedTextBox_2