Sandbox: JavaScript

Takes elements (inputs) with the data filter "Autocomplete" and creates a autocompletion ui for them that either completes against a list of terms supplied as a property of the element (data-autocomplete-tokens) or fetches them from a server. In both cases, the tokens must be an array of values. Example:

<input data-behavior="Autocomplete" data-autocomplete-tokens="['foo', 'bar', 'baz']"/>

Alternately, you can specify a url to submit the current typed token to get back a list of valid values in the same format (i.e. a JSON response; an array of strings). Example:

<input data-behavior="Autocomplete" data-autocomplete-url="/some/API/for/autocomplete"/>

When the values are fetched from the server, the server is sent the current term (what the user is typing) as a post variable "term" as well as the entire contents of the input as "value".

An additional data property for autocomplete-options can be specified; this must be a JSON encoded string of key/value pairs that configure the Autocompleter instance (see documentation below).

Less Component Required

Be sure to include components/autocomplete.less in your build.

Basic Usage

type some country names below...

<form class="form-horizontal">
  <div class="form-group">
    <div class="col-lg-5"><input name="a" class="form-control"
      data-behavior="Autocomplete" data-autocomplete-tokens="['Afghanistan',
     'Aland Islands', 'Albania', 'Algeria', 'American Samoa', 'Andorra', 'Angola',
     'Anguilla', 'Antarctica', 'Antigua And Barbuda', 'Argentina', 'Armenia', 'Aruba',
     'Australia', 'Austria', 'Azerbaijan', 'Bahamas', 'Bahrain', 'Bangladesh',
     'Barbados', 'Belarus', 'Belgium', 'Belize', 'Benin', 'Bermuda', 'Bhutan', 'Bolivia',
     'Bosnia And Herzegovina', 'Botswana', 'Bouvet Island', 'Brazil',
     'British Indian Ocean Territory', 'Brunei Darussalam', 'Bulgaria', 'Burkina Faso', 'Burundi',
     'Cambodia', 'Cameroon', 'Canada', 'Cape Verde', 'Cayman Islands',
     'Central African Republic', 'Chad', 'Chile', 'China', 'Christmas Island',
     'Cocos (Keeling) Islands', 'Colombia', 'Comoros', 'Congo', 'Cook Islands', 'Costa Rica', 'Cote D\'ivoire',
     'Croatia', 'Cuba', 'Cyprus', 'Czech Republic', 'Denmark', 'Djibouti', 'Dominica',
     'Dominican Republic', 'Ecuador', 'Egypt', 'El Salvador', 'Equatorial Guinea', 'Eritrea', 'Estonia',
     'Ethiopia', 'Falkland Islands (Malvinas)', 'Faroe Islands', 'Fiji', 'Finland',
     'France', 'French Guiana', 'French Polynesia', 'French Southern Territories',
     'Gabon', 'Gambia', 'Georgia', 'Germany', 'Ghana', 'Gibraltar', 'Greece',
     'Greenland', 'Grenada', 'Guadeloupe', 'Guam', 'Guatemala', 'Guernsey', 'Guinea',
     'Guinea-Bissau', 'Guyana', 'Haiti', 'Heard Island And Mcdonald Islands',
     'Holy See (Vatican City State)', 'Honduras', 'Hong Kong', 'Hungary', 'Iceland', 'India',
     'Indonesia', 'Iran, Islamic Republic Of', 'Iraq', 'Ireland', 'Isle Of Man',
     'Israel', 'Italy', 'Jamaica', 'Japan', 'Jersey', 'Jordan', 'Kazakhstan', 'Kenya',
     'Kiribati', 'Korea, Democratic People\'s Republic Of', 'Korea, Republic Of',
     'Kuwait', 'Kyrgyzstan', 'Lao People\'s Democratic Republic', 'Latvia', 'Lebanon',
     'Lesotho', 'Liberia', 'Libyan Arab Jamahiriya', 'Liechtenstein', 'Lithuania',
     'Luxembourg', 'Macao', 'Macedonia, The Former Yugoslav Republic Of', 'Madagascar',
     'Malawi', 'Malaysia', 'Maldives', 'Mali', 'Malta', 'Marshall Islands',
     'Martinique', 'Mauritania', 'Mauritius', 'Mayotte', 'Mexico',
     'Micronesia, Federated States Of', 'Moldova, Republic Of', 'Monaco', 'Mongolia',
     'Montenegro', 'Montserrat', 'Morocco', 'Mozambique', 'Myanmar', 'Namibia', 'Nauru', 'Nepal',
     'Netherlands', 'Netherlands Antilles', 'New Caledonia', 'New Zealand',
     'Nicaragua', 'Niger', 'Nigeria', 'Niue', 'Norfolk Island', 'Northern Mariana Islands',
     'Norway', 'Oman', 'Pakistan', 'Palau', 'Palestinian Territory, Occupied',
     'Panama', 'Papua New Guinea', 'Paraguay', 'Peru', 'Philippines', 'Pitcairn', 'Poland',
     'Portugal', 'Puerto Rico', 'Qatar', 'Reunion', 'Romania', 'Russian Federation',
     'Rwanda', 'Saint Helena', 'Saint Kitts And Nevis', 'Saint Lucia',
     'Saint Pierre And Miquelon', 'Saint Vincent And The Grenadines', 'Samoa',
     'San Marino', 'Sao Tome And Principe', 'Saudi Arabia', 'Senegal', 'Serbia',
     'Seychelles', 'Sierra Leone', 'Singapore', 'Slovakia', 'Slovenia',
     'Solomon Islands', 'Somalia', 'South Africa', 'South Georgia And The South Sandwich Islands',
     'Spain', 'Sri Lanka', 'Sudan', 'Suriname', 'Svalbard And Jan Mayen',
     'Swaziland', 'Sweden', 'Switzerland', 'Syrian Arab Republic', 'Taiwan, Province Of China',
     'Tajikistan', 'Tanzania, United Republic Of', 'Thailand', 'Timor-Leste',
     'Togo', 'Tokelau', 'Tonga', 'Trinidad And Tobago', 'Tunisia', 'Turkey', 'Turkmenistan',
     'Turks And Caicos Islands', 'Tuvalu', 'Uganda', 'Ukraine',
     'United Arab Emirates', 'United Kingdom', 'United States', 'United States Minor Outlying Islands',
     'Uruguay', 'Uzbekistan', 'Vanuatu', 'Venezuela', 'Viet Nam', 'Virgin Islands, British',
     'Virgin Islands, U.S.', 'Wallis And Futuna', 'Western Sahara', 'Yemen', 'Zambia', 'Zimbabwe']"></div>
  </div>
</form>

Getting data with Ajax

Note that the example below send a request that always returns the same result set (a few contry names that start with A).

<form class="form-horizontal">
  <div class="form-group">
    <div class="col-lg-5"><input name="a" class="form-control"
      data-behavior="Autocomplete" data-autocomplete-url="/sandbox/echo_json?data%5B%5D=Afghanistan&data%5B%5D=Aland+Islands&data%5B%5D=Albania&data%5B%5D=Algeria&data%5B%5D=American+Samoa&data%5B%5D=Andorra&data%5B%5D=Angola">
    </div>
  </div>
</form>

Configuration

Autocomplete is highly configurable. The behavior options (see docs below) are robust but also a bit complex. Study them carefully!

Behavior Options

These options apply only to the data- tag invocation. See the documentation below for JavaScript options, methods, and events.

Name type default description
minLength number 1 the minimum length of the string the user must enter before the suggestions are displayed; defaults to 1
selectMode string 'type-ahead'
  • true or selection - the user can type without the input value being highlighted or altered in any way. If they want to use a suggestion item, they must select it. Using the cursor keys the user can highlight a potential suggestion item and the input will be filled with the highlighted suggestion, while the portion of the suggestion that the user did not type will be selected so that they can continue typing if they wish.
  • type-ahead - as the user types the first suggestion item is selected and the 'missing' copy (the portion of the text the user has not yet typed) is selected. The user can use their cursor to move right and accept the suggestion or continue typing to refine the suggestion items.
  • pick - the user can type without the input value being highlighted or altered in any way. If they want to use a suggestion item, they must select it using the cursor keys to move up and down the suggestion items which will change the input value appropriately. However, in this case the portion of the input value they did not type is not selected.
overflow boolean true If set to true, the maxChoices option (not configurable in the behavior; so stuck at the default of 10) is ignored and all the available suggestion items are displayed
selectFirst boolean true whether to automatically select the first suggestion item even if it doesn't completely match the user entry. For instance: if the user types "aj" and the first suggestion is "ajax", a true setting for this option would select that first entry even though it doesn't completely match the user's entry.
multiple boolean true whether to split the user entered text into multiple values
separator string (a space) if multiple is true, this is the delemiter that will be used to seperate values; defaults to ' ' (comma)
allowDupes boolean true whether to allow duplicate suggestion items - only used if multiple is enabled
url string ~ If specified, the values are fetched via the url specified here. See the postVar option about how the parameters are passed.
postVar string 'term' the post variable name for the query string. This is the key for the user's input value (i.e. if the user is typing in "cookies" but has only typed in "coo" so far, the url in the arguments will be requested with term=coo if postVar is set to 'term').
tokens array ~ if url is not specified, then you must pass in an array of acceptable values for the tokens option. See example above.

Related Documentation

Note: Not all links in these work.

Script: Autocompleter

This class is extended by the other Autocomplete classes to add autocomplete functionality to text inputs.

  • license - MIT-style license
  • author & copyright - Harald Kirschner mail[at]digitarald[dot]de
  • homepage - http://digitarald.de/project/autocompleter/

These scripts are presented here for use with the Clientcide Libraries unaltered save for the fact that they have been split up from just Autocompleter.js into sub-files for Autocompleter.Local.js, and Autocompleter.Remote.js. They are amended with Autocompleter.Clientcide.js and Autocompleter.JSONP.js.

Tutorial/Demo

Notes

The Observer class that this distribution ships with has been replaced with IframeShim, and the Element method Element:getOffsetParent is now part of Element.Position.

Class: Autocompleter.base

This base class is extended by the the other Autocomplete classes. It accepts the following options, which are shared by all the other classes.

Implements

Options

  • minLength - (integer) the minimum length of the string the user must enter before the suggestions are displayed; defaults to 1
  • markQuery - (boolean) whether or not to wrap the portion of each suggestion that matches the user entry with a span tag (which gets the css class autocompleter-queried); defaults to true
  • width - (mixed) either the string 'inherit', which specifies that the suggestions dropdown should be as wide as the input, or an integer for the desired width in pixels; defaults to 'inherit'
  • maxChoices - (integer) the maximum number of suggestion items to display; defaults to 10
  • injectChoice - (function) the function that creates each suggestion item in the suggestions dropdown. The default is a function that injects an li element into the suggestion dropdown. This method is passed a token, which is one of the suggested values (which may or may not be a string, depending on what your server returns). Note that the element created by this function must have an attribute called 'inputValue' that returns the value to be inserted into the input when a suggestion item is selected.
  • customChoices - (element) an element container for the suggestion items; by default a ul is created on the fly, but you may specify a different container into which suggestion items will be injected.
  • className - (string) the class name to apply to the suggestion container; defaults to 'autocompleter-choices'
  • zIndex - (integer) the z-index of the suggestion dropdown; defaults to 42
  • delay - (integer) the period (in milliseconds) to wait befor the suggestion dropdown is displayed or its items updated after typing in the input; defaults to 400
  • observerOptions - (object) options passed on to the Observer class
  • fxOptions - (object or null) options passed to the effect (Fx.Tween) instance that fades the suggestions dropdown in/out; specifying null will mean no effect is used; defaults to {} (empty object)
  • autoSubmit - (boolean) whether to submit the form when the user chooses a suggestion item by hitting enter; defaults to false
  • overflow - (boolean) If set to true, the maxChoices option is ignored and all the available suggestion items are displayed; defaults to false
  • overflowMargin - (integer) if overflow is true and the user moves their selection (using the cursor keys) to an item that is outside the viewable list, this option specifies how far to jump down the suggestions dropdown to show more suggestion items; defaults to 25
  • selectFirst - (boolean) whether to automatically select the first suggestion item even if it doesn't completely match the user entry. For instance: if the user types "aj" and the first suggestion is "ajax", a true setting for this option would select that first entry even though it doesn't completely match the user's entry; defaults to false
  • filter - (function) if defined it will replace the default filter that is applied to the values returned as suggestion items. By default this method constructs a regular expression based on the following filterCase and filterSubset options.
  • filterCase - (boolean) if filter is not defined (and therefore the filter used is the default one) this setting will, if true, filter results using a case sensitive regex; defaults to false
  • filterSubset - (boolean) if filter is not defined (and therefore the filter used is the default one) this setting will, if true, allow for matches anywhere in the suggestion, otherwise the user entry must match the beginning of the suggestion; defaults to false
  • forceSelect - (boolean) whether to hide the suggestion dropdown only if the user selects a suggestion item or enters a value that is an exact match from the suggestion items; defaults to false
  • selectMode - (string) Three options:
    • true or selection - the user can type without the input value being highlighted or altered in any way. If they want to use a suggestion item, they must select it. Using the cursor keys the user can highlight a potential suggestion item and the input will be filled with the highlighted suggestion, while the portion of the suggestion that the user did not type will be selected so that they can continue typing if they wish. This is the default.
    • type-ahead - as the user types the first suggestion item is selected and the 'missing' copy (the portion of the text the user has not yet typed) is selected. The user can use their cursor to move right and accept the suggestion or continue typing to refine the suggestion items.
    • pick - the user can type without the input value being highlighted or altered in any way. If they want to use a suggestion item, they must select it using the cursor keys to move up and down the suggestion items which will change the input value appropriately. However, in this case the portion of the input value they did not type is not selected.
  • choicesMatch - (string) if defined, this string will be used to select for the choice element objects; defaults to null, which does not apply a filter.
  • multiple - (boolean) whether to split the user entered text into multiple values; defaults to false; the following two options affect the behavior of the split.
  • separator - (string) if multiple is true, this is the delemiter that will be used to seperate values; defaults to ', ' (comma space)
  • separatorSplit - (RegExp) if multiple is true, this regular expression will split the value into multiple values
  • autoTrim - (boolean) whether to remove leading and trailing spaces from the user entered text when the input loses or gains focus; defaults to true; (if multiple is true, empty values are also removed; i.e. "blah, , foo , bar" is cleaned up to "blah, foo, bar")
  • allowDupes - (boolean) whether to allow duplicate suggestion items; defaults to false
  • cache - (boolean) do not recompute (or re-fetch) suggestions for a value that was previously typed; defaults to true
  • relative - (boolean) if true, the suggestions dropdown element is injected immediately after the input. This allows the parent of the input to move and have the suggestions dropdown move with it; defaults to false

Events

  • onSelect - (function) This event is fired when the user moves the selection with the cursor keys or their mouse across a suggestion, highlighting it. The event is passed three arguments: the input that the autocompleter is attached to, the suggestion that is highlighted, and a boolean that denotes whether or not the input value should be updated with the highlighted suggestion.
  • onSelection - (function) This event is fired when the input is updated with a suggestion value. It is passed four arguments: the input that the autocompleter is attached to, the selection that is highlighted/selected, the current value of the input, and the value of the selected suggestion.
  • onShow - (function) This event is fired when the suggestions are displayed (with each key stroke). It is passed two arguments: the input that the autocompleter is attached to and the container of all the suggestions.
  • onHide - (function) This event is fired when the suggestions are hidden; it is passed the same two arguments as onShow.
  • onBlur - (function) This event is fired when the input's blur event occurs; passed one argument: the input that the autocompleter is attached to.
  • onFocus - (function) This event is fired when the input's focus event occurs; passed one argument: the input that the autocompleter is attached to.
  • onChoiceConfirm - (function) This event is fired when the user confirms the selection either by pressing 'Enter' or by clicking on a suggestion; passed one argument: the selection that is confirmed.

Autocompleter Method: destroy

This method removes the instance.

Syntax

myAutocompleter.destroy();

Script Autocompleter.Remote

Contains the classes for the Remote methods for Autocompleter.

Tutorial/Demo

Class Autocompleter.Ajax.Base

The base functionality for all Autocompleter.Ajax functionality.

Extends

Arguments

  1. input - (mixed) A string of the id for an Element or an Element reference of the form input to autocomplete.
  2. url - (string) the url to query for values based on user input.
  3. options - (object) key/value set of options.

Options

  • postVar - (string) the post variable name for the query string; defaults to 'value'. This is the key for the user's input value (i.e. if the user is typing in "cookies" but has only typed in "coo" so far, the url in the arguments will be requested with value=coo if postVar is set to 'value').
  • postData - (object) additional request data merged into the request.
  • ajaxOptions - (object) options for the Request instance.

Events

  • onRequest - (function) Callback executed when the request is initiated; passed four arguments: the input that the autocompleter is attached to, the instance of Request, the data sent for the query, and the value that the user has thus-far entered.
  • onComplete - (function) Callback executed when the request is completed; passed four arguments: the input that the autocompleter is attached to, the instance of Request, the data sent for the query, and the response from the server.

Notes

The Autocompleter.Ajax.Base class is not used directly but by its inheritors (see Autocompleter.Ajax.Json and Autocompleter.Ajax.Xhtml).

Class: Autocompleter.Ajax.Json

Extends Autocompleter.Ajax.Base to include Json support.

Extends

Syntax

new Autocompleter.Ajax.Json(input, url, options);

Arguments

All those specified in Autocompleter.Ajax.Base and Autocompleter.Base.

Example

new Autocompleter.Ajax.Json($('ajaxJson'), 'server/auto.php', {
    postVar: 'query'
});

Class: Autocompleter.Ajax.Xhtml

Extends Autocompleter.Ajax.Base to include Xhtml support.

Extends

Syntax

new Autocompleter.Ajax.Xhtml(input, url, options);

Arguments

All those specified in Autocompleter.Ajax.Base and Autocompleter.Base.

Example:

new Autocompleter.Ajax.Xhtml($('ajaxXhtml'), 'server/auto.php', {
    postData: {html: 1}, //some data to go along with the request
    //handle the data returned
    injectChoice: function(el) {
        var value = el.getFirst().get('html');
        el.inputValue = value;
        this.addChoiceEvents(el).getFirst().set('html', this.markQueryValue(value));
    }
});