Home » JavaScript » jQuery » JQuery Autocomplete Widget Example

About Era Balliu

Era Balliu
Era is a Telecommunications Engineering student, with a great passion for new technologies. Up until now she has been coding with HTML/CSS, Bootstrap and other front-end coding languages and frameworks, and her recent love is Angular JS.

JQuery Autocomplete Widget Example

By now everyone who has used a search engine has experienced auto-complete functionality at work. Originally intended to help those with physical limitations reduce the need for keyboard input, it has become commonplace on nearly every input element across a variety of software.

In this article we will look at the details of the JQuery Autocomplete widget; how to implement it, it’s wide range of capabilities and hopefully give you everything you need to know in order to start using it effectively and exercising it’s abilities to the fullest.

Want to be an jQuery Ninja?

Subscribe to our newsletter and download the jQuery Programming Cookbook right now!

In order to get you prepared for your jQuery development needs, we have compiled numerous recipes to help you kick-start your projects. Besides reading them online you may download the eBook in PDF format!

 

What we will have done by the end of the article

For this example, we own a bakery which is famous for it’s pies, with these changing daily. We are assigned to assist customers in finding today’s selection of pies.

So you know where we will ultimately want to end up, here is the complete code example:

<body>
  <script>
    $(function() {
      var availablePies = [
        "Apple",
        "Cherry",
        "Blueberry",
        "Strawberry",
        "Snozzleberry",
        "Pumpkin"
      ];
      $("#pies").autocomplete({
        source: availablePies
      });
    });
  </script>

  <div>
    <label for="pies">pies:</label>
    <input id="pies">
  </div>
</body>

Now let’s break it down, section by section.

HTML markup

We start with some HTML to get rolling. Kindly assume the presence of the required <html> and <head> tags.

We have an input element in our HTML as shown below, wrapped in a div and including a label to identify it:

<div>
    <label for="pies">pies:</label>
    <input id="pies">
  </div>

Setting up jQuery

First, to include the JQuery and JQueryUI library on our page we put the following snippets of code in the section of our markup:

<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>

With references to the necessary libraries in place and the elements defined in the HTML that we are intending to manipulate, we are set to dive into the widget itself.

Let’s dive in

The Autocomplete widget is one of the few JQuery widgets that must have at least one parameter to it: You must specify a source property on the widget. We will use a simple array as follows:

var availablePies = [
        "Apple",
        "Cherry",
        "Blueberry",
        "Strawberry",
        "Snozzleberry",
        "Pumpkin"
      ];

Obviously it would need values for the source property as this is where it gets the elements it is going to autocomplete from – without them, it would have no functionality.

Next we use the JQuery operator to grab the intended element as shown below:

$("#pies").autocomplete({
        source: availablePies
      });

Notice we have set the source property to the value of availablePies – the array we defined previously.

As of this moment, we have everything we need to get our example running. In your development environment of choice (I use Plunker for example) please enter the code as instructed above and execute it, entering the letter s for test purposes. We should see the results Strawberry and Willy Wonka’s favorite, Snozzleberry.

There are two other options when it comes to specifying the source option: a string (which resolves to a URL) or a function, which is a callback and is the most complicated to use. Examples of both will be shown below. Let’s move on for now.

Optimizing our Widget

The array implementation shown previous is, of course, the bare-bones minimum you need to get Autocomplete up and running. Some additional Options, Methods and Events can and will ultimately be used in your professional usage of this widget. We will explore a few of the more frequently used ones now.

minLength

minLength – specifies, as you might have guessed, the minimum number of characters a user must enter before receiving results. An example in code is below:

$("#pies").autocomplete({
        source: availablePies,
        minLength: 2
      });

Now if you test it with s you get nothing (no pie for you!) however if you add the t after the s – you get Strawberry! Nice job! Enjoy!

delay

Next we have the delay option which is the delay in milliseconds between when a keystroke occurs and when a search is performed, as written in the API:

$("#pies").autocomplete({
        source: availablePies,
        minLength: 2,
        delay: 500
      });

Again, entering st and after a very slight delay, we get our Strawberry pie… mmmm, pie.

source

Returning to the source ( “use the source, Luke…” ) we realize that nobody is likely to use static array of values to populate the source property. In a “professional” setting it is likely to be a remote source or something other than a simple local array. Let’s look at the use of a string to define the source option:

$("#pies").autocomplete({
        source: "http://example.com",
        minLength: 2,
        delay: 500
      });

In this instance, the plugin expects that the String specifies a URL resource that returns JSON data. This can be on the same host or a different host (in which case the results must be JSONP format).

A server-side script (language agnostic of course) must be in place to accept, via a GET request, the input from the plugin and will return the JSON data that matches the parameter it has received.

Finally and in conclusion, we have the most complicated of the source options: using a callback function. This option is the most flexible and with flexibility comes complexity in many programming scenarios, at least in my experience. On to it.

The function option can be used to connect any datasource to Autocomplete. The function is, as previously mentioned, a callback. It expects (and it will get) two parameters: a request object which has a single property, the input the user entered and a response callback which expects a single parameter response object, which is the data suggested to the user based on their input.

$("#pies").autocomplete({
        source: function ( request, response ) {
	logger (request.term);
	response ( ["Strawberry"] );
}
      });

Now in the above scenario the returned data in the response object can be in any of the previously mentioned formats. Like we said, it is the most flexible of the options.

So that’s an overview of the JQueryUI Autocomplete widget. Go forth and build your empire in code.

Download the source code

This was an example of jQuery Autocomplete Widget.

Download
You can download the full source code of this example here: AutocompleteWidget

Do you want to know how to develop your skillset to become a Web Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. Building web apps with Node.js

2. HTML5 Programming Cookbook

3. CSS Programming Cookbook

4. AngularJS Programming Cookbook

5. jQuery Programming Cookbook

6. Bootstrap Programming Cookbook

 

and many more ....

 

 

One comment

  1. Just saw a new excellent gallery cssnectar.com with good quality websites and updated daily. Very good for web design inspiration and not cluttered with advertisements as well.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

Want to take your WEB dev skills to the next level?

Grab our programming books for FREE!

Here are some of the eBooks you will get:

  • PHP Programming Cookbook
  • jQuery Programming Cookbook
  • Bootstrap Programming Cookbook
  • Building WEB Apps with Node.js
  • CSS Programming Cookbook
  • HTML5 Programming Cookbook
  • AngularJS Programming Cookbook