How to Create an Ajax Autocomplete Text Field: Part 5 | WebReference

How to Create an Ajax Autocomplete Text Field: Part 5

By Rob Gravelle


[next]
Digg This Add to del.icio.us

The AutocompleteList JavaScript File

In part 4 of this series, The AutocompleteList CSS File, we defined the appearance of our Autocomplete control using an external Cascading Style Sheet. This week we'll create a JavaScript file to manage the behavior of the Autocomplete control in the browser.

Import the JSON JavaScript Parser

In Part 3 - The Autocomplete Servlet, we brought the seven JSON utility classes into our project to facilitate working with JSON objects in the AutocompleteServlet. On the front-end, we'll use a JSON parser to convert the AJAX responseText to a JSON JavaScript Object. If you didn't download one back in the first installment, go to the https://www.JSON.org site and scroll to the bottom of the page. There are a couple of parsers under the JavaScript heading.

Once you've downloaded a parser, click on the "Import" command under "File: Import..." on the main menu to bring it into your project (See Figure 1).

Select "File System" from the "Import" dialog (See Figure 2).

Click the "Browse..." button next to the "From directory" dropdown to locate the folder which contains the JSON parser. Choose the folder and close the "Import from Directory" dialog. The folder you selected is now visible in the left window pane; the files contained therein will appear in the right pane. The checkboxes beside each item are used to flag it for import. Clicking on the the source folder checkbox on the left will automatically select all the files at once whereas selecting a checkbox next to a file will only select that file.

Next we have to specify the "Into Folder." Click the second "Browse" button and select the "WebContent" folder from the "Import from directory" dialog (not shown), since it's the root for our Web files (See Figure 3).

You'll now be able to see the new file in the "Project Explorer" pane, along with the AutocompleteList.css file that we created in part 4.

Create the AutocompleteList.js File

It was in "Part 4: The Autocomplete.css File" that we also added some menu items to the "New" menu in order to simplify the creating of new files. Select the "WebContent" folder in the "Project Explorer" pane and press the "Alt+Shift+N" keys to bring up the "New" submenu, which now include the "JavaScript" file type (See Figure 4).

Select the "JavaScript" item to bring up the "New JavaScript File" dialog. Enter "AutocompleteList" in the "File name" textbox and click on the "Finish" button to add the new JavaScript file in the WebContent folder. The extension will be added automatically (See Figure 5).

You'll notice that this action also opened a new editor in the main window pane. We're now ready to begin coding


[next]