#{extends 'jqueryui/layout.html'/} #{set title:'Autocomplete'/} #{set 'moreScripts'} #{/set}

Autocomplete - label only

Use a label-only autocomplete widget to suggest text values for an input field.

Demo

Type to populate the list, and select a label from the list.

Client

The widget is based on the the following input element, using the data-url attribute value for the server-side data source.

<input name="location" class="autocomplete" data-url="@{jqueryui.Autocomplete.label()}">

The autocomplete.js JavaScript applies the jQuery UI autocomplete plug-in to the input element.

#{includeVerbatim '/public/javascripts/autocomplete.js'/}

Server

The jqueryui.Autocomplete.label(String term) action renders a JSON-encoded list of strings that match the user-entered term parameter.

#{set 'label'} public static void label(final String term) { final List response = new ArrayList(); for (String label : TestData.locations()) { if (label.toLowerCase().startsWith(term.toLowerCase())) { response.add(label); } if (response.size() == AUTOCOMPLETE_MAX) { break; } } renderJSON(response); } #{/set}
${label}

Note that there is no view template, because renderJSON renders a response directly.

Autocomplete - label and value

Use a label/value autocomplete to suggest input options that have a separate label and value.

Demo

Type to populate the list, then select the value for a particular label.

Submit the form to submit the numeric value, but not the label.

Client

The HTML input is almost the same as the example above, except that the form control name is different, because the submitted value will be an ID value instead of a string label.

<input name="location.id" class="autocomplete-value"
data-url="@{jqueryui.Autocomplete.value()}">

This client implementation uses more JavaScript in autocomplete-value.js to handle label/value pairs, with an additional hidden field in the form.

#{includeVerbatim '/public/javascripts/autocomplete-value.js'/}

Server

The jqueryui.Autocomplete.value(String term) action renders a JSON-encoded list of label/value pairs that match the user-entered term parameter.

#{set 'value'} public static void value(final String term) { final List response = new ArrayList(); int index = 1; for (String label : TestData.locations()) { final String value = String.valueOf(index); if (label.toLowerCase().startsWith(term.toLowerCase())) { response.add(new AutocompleteValue(value, label)); } if (response.size() == AUTOCOMPLETE_MAX) { break; } index++; } renderJSON(response); } #{/set}
${value}
#{includeVerbatim '/app/models/jqueryui/AutocompleteValue.java'/}