Monday, August 27, 2012

JQuery .autocomplete Basics


So let's say I want to have a text field on a website that prompts users with values that they have previously entered. The solution that I have found myself using over and over is the autocomplete function in Jquery. 

So let's start from basics. In the heading of your page you will need a couple of references:

<script type='text/javascript' src='/jquery/jquery-1.7.1.min.js'></script>
<script type='text/javascript' src="/jQuery/jquery-ui-1.8.18.custom.min.js"></script>

Since this posting there are newer versions of the libraries, but you should be able to get the latest version at the following addresses.

jquery-1.7.1.min.js can be found @ http://jquery.com/download/
jquery-ui-1.8.18.custom.min.js can be found @ http://jqueryui.com/download.

Please feel free to mix and match when pulling a library from http://jqueryui.com/download, it only makes sense to pull what you will need for the site to keep load times small.

So in its simplest and least useful form the autocomplete function can be called like this:

$(function () { $(".SomeClass").autocomplete({source: [“Shop”, “Shopping”, “Writing”]});}); or

$(function () { $("#SomeElement").autocomplete({source: [“Shop”, “Shopping”, “Writing”]});});

Source option must be specified on the autocomplete function.

Use the first scenario when there are multiple textboxes or text areas on a form where you want the list to pop-up.  Use the second when there is a specific textbox or text area where you want to apply the list.  The example above uses a static array and really doesn't do much for us, so lets move on one more step.

With the above code you can define a list of items (in our case Shop, Shopping, and Writing) as an autocomplete list which will appear below a text field as the user types.



So, what do we do when we have a list that is longer than 3 items? What if we have a list that is 30,000 items?  Well, first, you don't put it in an array on the page.  To return a smaller list I would use ajax to call a webservice, or webmethod and the minLength option to set the minimum number of characters the user has to enter before the methods are called.  minLength defines how many letters the user has to enter in a text box before the list will appear.

$(function () { $(".SomeClass").autocomplete(
{
source: [“Shop”, “Shopping”, “Writing”],
minLength: 3
});
});

Now for an intermediate example (ajax): 

In the following example, we call a static method on the page to return our list. 
<script type="text/javascript">

$(function () { $(".SomeClass").autocomplete
({
source:
function (request, response) {
$.ajax
({
url: "Default.aspx/GetCategories", //Page / Static Webmethod
data: "{name:" + JSON.stringify(request.term) + "}", //The parameter name on the method GetCategories is “name” and is of type string.
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response(data["d"]); //Returns an array of strings
},
error: function (xHr, callStatus, errorThrown) {
alert(callStatus);
}
});
},
minLength: 1 //Call this after one letter is typed.
});
});
</script>



Lets break this one down.  We have a source, and minLength as we defined in earlier examples, but instead of an array we are calling a static webmethod on the page called GetCategories. 

[WebMethod]
public static List<string> GetCategories(string name)
{
return new List<string>{“Shop”, “Shopping”, “Writing”};//Do some linq or EF magic here.
}

GetCategories takes a paramater named "name" and returns a list of strings. 



If you copy the code above, there are only a few options that  you will need to change in order to start using the autocomplete function.  I want to start with the error handling.  When I first saw the error function I didn't know what the parameters being passed were.  Here are the definitions or the parameters.

xHr is an XMLHttpRequest
callStatus will contain one of the following values: "timeout", "error", "abort", "parsererror", or null
errorThrown contains an optional exception

A better explaination can be found here.  Just search for the word "error".

Now look at the success option.  The success option returns an array of strings generated by our WebMethod GetCategories.   You can see the formatting of the data in the screen shot below:




The only other two options you will need to change are the url and the data options.
As the name states, the url option defines the url.
url:"Default.aspx/GetCategories", //Page / Static Webmethod

The data option defines the parameters for the method on the url and the value being passed.
data:"{name:"+ JSON.stringify(request.term) + "}", //The parameter name on the method GetCategories is “name” and is of type string.
 
With the data option it is very important to match the name of your parameter exactly.  Hope this helps!  Look for a forthcoming post on using the select option, and some of the fun things we can do with that.