This is a mirror of official site: http://jasper-net.blogspot.com/

jQuery Tutorial - Creating an Autocomplete Input Textbox

| Monday, February 14, 2011
With jQuery 1.8 came a brand new widget - the autocomplete input field. If used correctly, like in the case of Google's search suggestions, autocomplete can provide a major boost in productivity. Today's tutorial is going to demonstrate how to build and populate one of these autocomplete inputs. We're going to make two identical examples that get their data from two different sources - one will be client-side and the other will be server-side using PHP.

The example dataset will include all of the presidents of the United States. As you begin typing, the input field will automatically popup with suggestions that match your query. Feel free to play with the example below. Some good examples would be "George Washington" or "Abraham Lincoln".

Client Side

The first example we'll build today will be entirely client-side. This is by far the easiest approach to take, but obviously the least powerful. The jQuery demo page for autocomplete has a very nice example that we're basically going to replicate with different data. Let's start with the html.

<html>
 <link type="text/css" rel="stylesheet" media="all"
      href="jquery-ui-1.8.9.custom.css" />
 <script type="text/javascript" src="jquery-1.4.4.min.js"></script>
 <script type="text/javascript" src="jquery-ui-1.8.9.custom.min.js"></script>
 <script type="text/javascript" src="presidents.js"></script>
 <body>
   <label for="presidentsClientInput">Select President (client-side): </label>
   <input id="presidentsClientInput" />
 </body>
</html>
Most of the code here is just getting jQuery included. The important part is the label and the input field. The input needs to have an id so we can reference it later and turn it into an autocomplete field.

Let's jump into the javascript now - the source of presidents.js. The first thing we need is a datasource, which should be a simple array of values. jQuery does the work of iterating through these values to find the ones that match the text already in the input field.

$(function() {
       var presidents = [
               "George Washington",
               "John Adams",
               "Thomas Jefferson",
               "James Madison",
               "James Monroe",
               "John Quincy Adams",
               "Andrew Jackson",
               "Martin Van Buren",
               "William Henry Harrison",
               "John Tyler",
               "James Knox Polk",
               "Zachary Taylor",
               "Millard Fillmore",
               "Franklin Pierce",


Read more: Switch on code

Posted via email from Jasper-net

0 comments: