<script>
function autocomplete(fieldId, ajaxurl) {
$('#'+fieldId).autocomplete({
source: function( request, response ) {
$.ajax({ type: "GET",
url: ajaxurl,
dataType: "json",
cache:false,
data: { userInput: request.term},
statusCode: { 401: function() { alert("Page Not Found"); } }})
.fail(function() { alert("Session Timed Out"); })
.done(
function( data )
{
response( $.map( data, function( item ) {
return {
label: item.sfullName,
value: item.sfullName
}
}));
});
},
minLength: 2,
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
}
</script>
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
{
if(session.getAttribute("associateNamesList")!=null)
{
associatesList=(List<AssociateSearchBean>)session.getAttribute("associateNamesList");
}
else
{
//get all usernames from db using select query into a list
associatesList =objDB.getAssociateNames();
session.setAttribute("associateNamesList",associatesList);
}
//here userinput is whatever user types which should be more than 3 characters
List<AssociateSearchBean> suggestions = getAssociates(associatesList,userInput);
String suggestionsJson = gson.toJson(suggestions); /Convert Java object to JSON format
writeTextResponse(response, suggestionsJson);
}
public List<AssociateSearchBean> getAssociates(List<AssociateSearchBean> associateSearchResultList,final String userInput) {
List<AssociateSearchBean> filteredlist = new ArrayList<AssociateSearchBean>();
int count = 0;
for (AssociateSearchBean associateName : associateSearchResultList) {
if(associateName!=null)
{
if (userInput!=null && userInput.length() >= 2 && associateName.getFirstName().toLowerCase().startsWith(userInput.toLowerCase())) {
filteredlist.add(associateName);
count++;
continue;
}
if (userInput!=null && userInput.length() >= 2 && associateName.getLastName()!=null && associateName.getLastName().toLowerCase().startsWith(userInput.toLowerCase())) {
filteredlist.add(associateName);
count++;
}
//so that only first 12 entries are displayed
if (count >= 12) {
break;
}
}
}
return filteredlist;
}
protected void writeTextResponse( HttpServletResponse resp, String content )
{
try
{
resp.setContentType("text/html");
resp.setHeader("Cache-Control", "no-cache");
resp.getWriter().print(content);
resp.getWriter().close();
}
catch (Exception ex)
{
logger.logDebug(ex.getMessage());
}
}
<script type="text/javascript">
$(document).ready(function() {
autocomplete('sFullNameId','<%=request.getContextPath()%>/searchADPian.do?action=processAutoSearch');
});
</script>