Tuesday July 29, 2008
TOTD #39: Prototype/Script.aculo.us Autcomplete widget with MySQL, GlassFish, NetBeans
There are several JavaScript libraries that can be embedded in your
webapplication to create a visually appealing interface. Script.aculo.us is
one of the popular ones and is built on the Prototype JavaScript
Framework. The library provides an easy-to-use, cross-browser
user interface JavaScripts that allows you to create fancy effects
commonly visible on web pages these days.
This blog entry gets you started by using Ajax.Autocompleter
that allows for server-powered autocompleting of text fields.
Basically, you type a character in a text field and suggestions for
possible correct values starting with that character are
shown . This is achieved by by sending an Ajax request to the
data source on server, passing the typed character in the request and
processing the response to display on the web page. This effect was
first popularized by Google
Suggest.
In this TOTD (Tip
Of The Day) we will create
a simple web application with a text field in a JSP page that will use
Servlet as the data source. The Servlet retrieves the parameter from
the RequestContext, uses Java Persistence API to query the database and
return response in the expected format. We will use:
| @NamedQuery(name = "States.findLikeName", query = "SELECT s FROM States s WHERE LOWER(s.name) LIKE :searchString"), |

|
String searchString = request.getParameter("autocomplete_parameter"); List<States> list = em.createNamedQuery("States.findLikeName"). setParameter("searchString", searchString.toLowerCase() + "%"). getResultList(); out.println("<ul>"); for (int i = 0; i < list.size(); i++) { States s = list.get(i); out.println("<li>" + s.getName() + "</li>"); } out.println("</ul>"); |
|
<script src="javascripts/prototype.js"
type="text/javascript"></script> <script src="javascripts/scriptaculous.js?load=effects,controls" type="text/javascript"></script> <script type="text/javascript"> window.onload = function() { new Ajax.Autocompleter("autocomplete", "autocomplete_choices", "/Autocomplete/StatesServlet", {}); } </script> |
|
<input type="text" id="autocomplete"
name="autocomplete_parameter"/> <div id="autocomplete_choices" class="autocomplete"></div> |
| .autocomplete { position:absolute; width:250px; background-color:white; margin:0px; padding:0px; overflow:hidden; } .autocomplete ul { list-style-type:none; margin:0px; padding:0px; overflow:auto; } .autocomplete ul li.selected { background-color: #ffb;} .autocomplete ul li { list-style-type:none; display:block; margin:0; padding:2px; height:32px; cursor:pointer; } |
| <LINK href="stylesheets/autocompleter.css" rel="stylesheet" type="text/css"> |





|
window.onload = function() { new Ajax.Autocompleter("autocomplete", "autocomplete_choices", "/Autocomplete/StatesServlet", { minChars: 2 }); } |
Posted by Arun Gupta in web2.0 | Comments[6]
|
|
|
|
|
Today's Page Hits: 1033
Total # blog entries: 1002