Mar.28

How to use jQuery UI Autocomplete widget

Posted on March 28, 2011
How to use jQuery UI Autocomplete widget

I was working at one of my company’s customer site, and while I was investigating a problem with the customer at one of our system’s pages, I found him selecting a value from a more than 3000 items drop down list!!!? I wondered and asked him, how can you find your desired item?… he replied it is really a hard job, but what can I do?

I spent two days and came back to him with the auto complete solution, he was really impressed, so I am writing today to let you know how to implement such a feature…

There is a lot of ready made auto complete components freely available on the internet, but I choose the jQuery UI one because of my previous knowledge of jQuery, and the wide community of it, and the most impressing feature of the jQuery that you will never need to change any thing in your html, you will select what you want from the DOM, and do what you need on it, all what you need is that the element should has an id attribute, let’s see…

First thing you have a very normal html file – it may be a jsp, jspx, aspx, or any file that will be rendered to html on the browser, in that file we have the input text that we want to add the auto complete functionality to it, the only required thing for our work is to add the id attribute for that element – most probably it is already exists

<body>
 <label for="txtFullName">Full Name "Enter 3 letters..."</label>
 <input id="txtFullName" type="text">
</body>

Then you have to include jQuery, and jQuery UI libs to your file, I recommend going to:

http://docs.jquery.com/Downloading_jQuery

and

http://jqueryui.com/download

And download the latest versions of the, then include them in your file

<link type="text/css" href="css/start/jquery-ui-1.8.11.custom.css" rel="stylesheet" />
<script type="text/javascript" src="js/jquery-1.5.1.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.11.custom.min.js"></script>

Note: do not forget to include the jQuery UI stule sheet file also as mentioned above

Now you are ready to use jQuery lib, and jQuery UI widgets, we will write our js code in the same file but for production it it is better to let the js codes be in separate files, now add this to your file:

<script>
var availableNames = [
 "Amr Amr",
 "Ali Ali",
 "Badr Badr",
 ];
$(document).ready(function(){
 $("#txtFullName").autocomplete({
 source: availableNames
 });
 });
</script>

Note: that we selected the text field by its id, then added the auto complete functionality to it, let’s try that:

As you can see this is the minimal configuration for the widget, but it is the start, let’s go deeper

Let’s start with moving the business from a static data, to a dynamic data generated from a server side code, to do this you have to set the source option to a callback method that will do an Ajax call to get the filtered data based on the entered letters and return the list of objects with the proper format

I will implement my back end as a servlet returns this string regardless the key sent – you can do the filtration logic your self

[{ "value":"Amr", "label":"Amr", "extra":"1" }, { "value":"Ali", "label":"Ali",  "extra":"2" }, { "value":"Badr", "label":"Badr", "extra":"3" }]

Note that this is a json list of objects, each object must has the value, and label attribute, the the widget will make use of them, also you can send any extra data like and id or any data you need at the client side, for example I am sending an attribute named extra to use its value and put it in a hidden field

<script>
function getFilteredNames(request, response){
 $.ajax({
 url: "http://localhost:8080/Autocomplete-Test/GenericServlet",
 cache: false,
 dataType: "json",
 data: $.extend({op:"1", key:request.term},request),
 success: function(data) {
 response(data);
 }
 });
}

function setHiddenField(event, ui){
 $('#hiddenField').val(ui.item.extra);
}

$(document).ready(function(){
 $("#txtFullName").autocomplete({ source : getFilteredNames, minLength: 3, select: setHiddenField });
 });
</script>

At this point you should get the same result, but the data is coming form the server not statically set on the client

As shown, I am using the getFilteredName method to do an Ajax call to my GenericServlet passing to it two params, actually I am not using them but if you are going to do real filtered selection you have to use them, and return the json result list based on them, also I am setting the minLength to 3 as you have to enter at least three chars to before the widget start working, this is important if you have a very large expected result size for short key – one or two chars, also I used the select option to call a method after selecting an item from the result list, in that method I set the value of a hidden field to the extra data I sent with the result list form the server, in real scenarios you may set a hidden field with an employee Id to be submitted to the server with the page

Note: the extend option to send all the needed parms to server side

Note: the dataType is set to json to parse the returned data from the server as json list of object

Note: I am setting the cache to false so that every time I force the Ajax to work it will get the data again from the server, I am doing this because another business in my page is changing the data on the server, you may change this to true for better performance

Note: that the elements’ ids used are the client side ids, means that if for example your page is a JSF page you have to add the form id before the component id separated by ‘:’, and this ‘:’ should be escaped by ‘\’ in JavaScript

References:

http://jqueryui.com/demos/autocomplete

Tags:
Share this Story:

About Amr

Senior Full-Stack developer working for Clevertech, and
Leading my own freelancing team.

Comments(0)

Leave a comment

Comment