Stripes framework and jQuery Autocomplete

December 16th, 2008 by Samuel Santos Leave a reply »

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:
Stripes and jQuery Autocomplete example

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.

Get this example source code!

Related Posts

Advertisement

37 comments

  1. AskApache says:

    This is turning into one of my favorite blogs, awesome content samaxes… jQuery is still totally foreign to me, thanks.

  2. nila says:

    Hi,
    I tried this example, is not working. could you please share working script/war file
    thanks in advance

  3. Hey Nila,

    At the end of the article you have a “Get this example source code!” link pointing to a complete working example.

  4. nila says:

    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,

  5. You can change the width by changing the width option of the plugin.

    $(document).ready(function() {
        $('#city').autocomplete({
            url: '/Autocomplete.action?autocomplete=',
            minChars: 1,
            max: 10,
            width: 150,
            scroll: false
        });
    })
    
  6. nila says:

    thanks Sam for the quick response. this helped me a lot.

  7. muthu kumar says:

    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

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

  9. nila says:

    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

  10. You can pass the value of the auto_text1 as a parameter to the server and filter the elements to return to the auto_text2. Example:

    $(document).ready(function() {
        $('#auto_text2').autocomplete({
            url: '/Autocomplete.action?autocomplete=&text1=' + $('#auto_text1').val(),
            minChars: 1,
            max: 10,
            width: 150,
            scroll: false
        });
    })
    
  11. nila says:

    thanks Sam.

    my apologies this how the code looks like,

    jsp code

    <stripes:text name='text1' id='text1' />
    <stripes:text name='text2' id='text2' />
    

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

  12. You cannot use the url '/xref/Search.action?autocomplete_text2=&text1='+ $('#autocomplete_text1').val() since you don’t have any HTML element with the id autocomplete_text1.

    The url '/xref/Search.action?autocomplete_text2=&text1='+ $('#text1').val() should work fine if you have the setter for the property text1 in your ActionBean. Pay attention to not use &amp; instead of & in your JavaScript.

  13. nila says:

    thanks Sam. Still it is still printing null. Do you have any working example.
    thanks in advance,
    nila

  14. Sorry Nila, but I don’t have any example with dependent combo boxes.

  15. nila says:

    oh!!! thanks any way. i will try , if it works i will post the code.

  16. nila says:

    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

  17. Try debugging it with Firebug: console.log($('#text1'));

  18. nila says:

    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

  19. Irshad says:

    Hi Sam,
    Do you a working jquery autocomplete based on Spring MVC. Can u suggest how to get it done.

    –Irshad.

  20. Sorry Irshad, I do not work with Spring MVC.

  21. chum says:

    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

  22. chum says:

    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

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

    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

    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.

  24. chum says:

    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

  25. Hi chum,

    You can’t directly access jsp files under the WEB-INF folder.
    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 war file inside target folder to your server.
    It will deploy under the / context path (e.g. http://localhost:8080/).

  26. s says:

    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?

  27. s says:

    opss, sorry..
    i didn’t notice it was STRIPES lib

  28. Koray says:

    how can i do selectbox item selection change trigger autocomplete..thanks

  29. SarcasticTrade says:

    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

  30. Alamgir Kahn says:

    Samuel — Great post. Thanks. VERY helpful!

  31. Devendra Jain says:

    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?

  32. Vishnu says:

    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

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

  34. Kannas says:

    @nila you can use
    select: function instead to pass selected value of your autocompletedTExtBox_1 to autocompletedTextBox_2

Leave a Reply