Chapter 9. Autocompletion

Autocompletion is a mechanism frequently used in modern websites to provide the user with a list of suggestions for the beginning of the word he has typed in a text box. He can then select an item from the list, which will be displayed in the input field. This feature prevents the user from having to enter an entire word or a set of words.

Basic Principles of Autocompletion

Suppose we want to write the HTML code to display the list of suggestions shown in Figure 9-1, which appears when users type the letter “p.” This displays a list in which each element contains at least one letter “p.”

List of suggestions

Figure 9-1. List of suggestions

The input field is represented by an <input> whose ID is book:

<script src = jquery.js></script>
<script src = jqueryui/js/jquery-ui-1.8.16.custom.min.js></script>

<link rel=stylesheet type=text/css
      href=jqueryui/css/smoothness/jquery-ui-1.8.16.custom.css />

<h3>Enter the name of the book:</h3>
<input id=book />

<script>

// array of items to be proposed in the list of suggestions
var books = ["Web development with J2EE", "Practical CSS & JavaScript",
             "Practical Ruby on Rails", "Introduction to HTML & CSS",
             "jQuery UI"];

$("input#book").autocomplete ({
  source : books
});

</script>

In the <script> tag of the HTML page, we need to indicate both the list of suggestions (var books) and that the input field must be observed in order to display the list ...

Get jQuery UI now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.