jQuery UI API - Autocomplete Widget

Categories

Widgets

Usage

Description:The autocomplete feature searches and filters based on user input, allowing users to quickly find and select from a preset list of values.

Version added:1.8

Any field that can receive input can be converted into an Autocomplete, i.e.,<input>input elements,<textarea>textarea elements, andcontenteditableelements with a contenteditable attribute.

By giving focus to the Autocomplete field or typing characters into it, the plugin starts searching for matching entries and displays a list of values to choose from. By typing more characters, the user can filter the list to get better matches.

This widget can be used to select previously selected values, such as entering article tags or entering email addresses from an address book. Autocomplete can also be used to populate related information, such as entering a city name to get the postal code of that city.

You can get data from a local source or a remote source: a local source is suitable for small data sets, such as an address book with 50 entries; a remote source is suitable for large data sets, such as a database with hundreds or thousands of entries. For more information about custom data sources, seesourcethe documentation for the option.

Keyboard Interaction

When the menu is open, the following keyboard commands are available:

  • UP - Move focus to the previous item. If on the first item, move focus to the input. If on the input, move focus to the last item.
  • DOWN - Move focus to the next item. If on the last item, move focus to the input. If on the input, move focus to the first item.
  • ESCAPE - Close the menu.
  • ENTER - Select the currently focused item and close the menu.
  • TAB - Select the currently focused item, close the menu, and move focus to the next focusable element.
  • PAGE UP/DOWN - Scroll a screenful of items (based on the height of the menu).

When the menu is closed, the following keyboard commands are available:

  • UP/DOWN - If satisfied,minLengththen open the menu.

Theming

The Autocomplete Widget usesthe jQuery UI CSS Frameworkto define the styles of its look and feel. If you need to use styles specific to the Autocomplete Widget, you can use the following CSS class names:

  • ui-autocomplete: Used to display the matchingmenu.
  • ui-autocomplete-input: The input element instantiated by the Autocomplete Widget.

Dependencies

Additional Notes

  • This widget requires some functional CSS, otherwise it will not work. If you create a custom theme, use the widget-specific CSS file as a starting point.
  • This widget programmatically operates on the element's value, so when the element's value changes, it will not trigger the nativechangeevent.

Quick Navigation

Options Methods Extension Points Events

Options Type Description Default Value
appendTo Selector The element to which the menu should be appended. When this value isnull, the parent element of the input field will check forui-frontclass. If an element withui-frontclass is found, the menu will be appended to that element. If no element withui-frontclass is found, the menu will be appended to the body regardless of the value.

Note: When the suggestion menu is open,appendTothe option should not be changed.

Code examples:

Initialize an autocomplete with the specifiedappendTooption:

$( ".selector" ).autocomplete({ appendTo: "#someElem" });
    

After initialization, get or set theappendTooption:

// getter
var appendTo = $( ".selector" ).autocomplete( "option", "appendTo" );
 
// setter
$( ".selector" ).autocomplete( "option", "appendTo", "#someElem" );
    
null
autoFocus Boolean If set totrue, when the menu is displayed, the first item will automatically get focus.

Code examples:

Initialize an autocomplete with the specifiedautoFocusoption:

$( ".selector" ).autocomplete({ autoFocus: true });
    

After initialization, get or set theautoFocusoption:

// getter
var autoFocus = $( ".selector" ).autocomplete( "option", "autoFocus" );
 
// setter
$( ".selector" ).autocomplete( "option", "autoFocus", true );
    
false
delay Integer The delay between a keystroke and the execution of the search, in milliseconds. For local data, a zero delay is meaningful (more responsive), but for remote data it creates a heavy load and reduces responsiveness.

Code examples:

Initialize an autocomplete with the specifieddelayoption:

$( ".selector" ).autocomplete({ delay: 500 });
    

After initialization, get or set thedelayoption:

// getter
var delay = $( ".selector" ).autocomplete( "option", "delay" );
 
// setter
$( ".selector" ).autocomplete( "option", "delay", 500 );
    
300
disabled Boolean If set totrue, the autocomplete is disabled.

Code examples:

Initialize an autocomplete with the specifieddisabledoption:

$( ".selector" ).autocomplete({ disabled: true });
    

After initialization, get or set thedisabledoption:

// getter
var disabled = $( ".selector" ).autocomplete( "option", "disabled" );
 
// setter
$( ".selector" ).autocomplete( "option", "disabled", true );
    
false
minLength Integer The minimum number of characters the user must type before a search is executed. For local data with only a few entries, it is usually set to zero, but when a single character search would match thousands of entries, setting a high value is necessary.

Code examples:

Initialize an autocomplete with the specifiedminLengthoption:

$( ".selector" ).autocomplete({ minLength: 0 });
    

After initialization, get or set theminLengthoption:

// getter
var minLength = $( ".selector" ).autocomplete( "option", "minLength" );
 
// setter
$( ".selector" ).autocomplete( "option", "minLength", 0 );
    
1
position Object Specifies the position of the suggestion menu in relation to the associated input element.ofThe option defaults to the input element, but you can specify another positioning element. For more details on the various options, seejQuery UI Position。

Code examples:

Initialize an autocomplete with the specifiedpositionoption:

$( ".selector" ).autocomplete({ position: { my : "right top", at: "right bottom" } });
    

After initialization, get or set thepositionoption:

// getter
var position = $( ".selector" ).autocomplete( "option", "position" );
 
// setter
$( ".selector" ).autocomplete( "option", "position", { my : "right top", at: "right bottom" } );
    
{ my: "left top", at: "left bottom", collision: "none" }
source Array or String or Function( Object request, Function response( Object data ) ) Defines the data to be used, and must be specified.

Regardless of the variable you use, the label is always treated as text. If you want the label to be treated as html, you can useScott González' html extension. The demo focuses onsourcethe different variations of the option - you can find the one that matches your usage and view the related code.

Multiple types are supported:

  • Array: An array that can be used for local data. Two formats are supported:
    • String array:[ "Choice1", "Choice2" ]
    • An array of objects withlabelandvalueattributes:[ { label: "Choice1", value: "value1" }, ... ]
    The label attribute is displayed in the suggestion menu. When the user selects an item, the value is inserted into the input element. If only one attribute is specified, that attribute is treated as both the label and the value. For example, if you only providevaluethe attribute, the value is also treated as the label.
  • String: When using a string, the Autocomplete plugin expects the string to point to a URL resource that can return JSON data. It can be on the same host or on a different host (must provide JSONP). The Autocomplete plugin does not filter the results, but instead, through atermfield, adds a query string for the server-side script to filter the results. For example, ifsourcethe option is set to"http://example.com", and the user typesfoo, the GET request would behttp://example.com?term=foo. The format of the data itself can be the same as the format of the local data described earlier.
  • Function: The third variable, a callback function, provides the greatest flexibility and can be used to connect any data source to the Autocomplete. The callback function accepts two parameters:
    • anrequestobject, with atermattribute, representing the value in the current text input. For example, if the user types in the city field"new yo", then Autocomplete term is equivalent to"new yo"。
    • aresponsecallback function, providing a single parameter: the data suggested to the user. The data should be filtered based on the provided term, and can be in any of the local data formats described above. Used to provide a custom source callback to handle errors during the request. Even if an error is encountered, you must callresponsethe callback function. This ensures the widget is always in the correct state.

    When filtering local data, you can use the built-in$.ui.autocomplete.escapeRegexfunction. It accepts a string argument, escapes all regular expression characters, and makes the result safe to pass tonew RegExp()。

Code example:

Initialize the autocomplete with the specifiedsourceoptions:

$( ".selector" ).autocomplete({ source: [ "c++", "java", "php", "coldfusion", "javascript", "asp", "ruby" ] });
    

After initialization, get or set thesourceoption:

// getter
var source = $( ".selector" ).autocomplete( "option", "source" );
 
// setter
$( ".selector" ).autocomplete( "option", "source", [ "c++", "java", "php", "coldfusion", "javascript", "asp", "ruby" ] );
    
none; must be specified

Methods Returns Description
close() jQuery (plugin only) Closes the Autocomplete menu. When used with thesearchmethod, it can be used to close an open menu.
  • This method does not accept any arguments.

Code example:

Invoke the close method:

$( ".selector" ).autocomplete( "close" );
    
destroy() jQuery (plugin only) Completely remove the autocomplete functionality. This will return the element to its pre-initialization state.
  • This method does not accept any arguments.

Code example:

Invoke the destroy method:

$( ".selector" ).autocomplete( "destroy" );
    
disable() jQuery (plugin only) Disable the autocomplete.
  • This method does not accept any arguments.

Code example:

Invoke the disable method:

$( ".selector" ).autocomplete( "disable" );
    
enable() jQuery (plugin only) Enable the autocomplete.
  • This method does not accept any arguments.

Code example:

Invoke the enable method:

$( ".selector" ).autocomplete( "enable" );
    
option( optionName ) Object Gets the value currently associated with the specifiedoptionNameoption.
  • optionName
    Type: String
    Description: The name of the option to get.

Code example:

Invoke the method:

var isDisabled = $( ".selector" ).autocomplete( "option", "disabled" );
    
option() PlainObject Gets an object containing key/value pairs that represent the current autocomplete options hash.
  • This method does not accept any arguments.

Code example:

Invoke the method:

var options = $( ".selector" ).autocomplete( "option" );
    
option( optionName, value ) jQuery (plugin only) Sets the value of the autocomplete option associated with the specifiedoptionNameoption.
  • optionName
    Type: String
    Description: The name of the option to set.
  • value
    Type: Object
    Description: The value to set for the option.

Code example:

Invoke the method:

$( ".selector" ).autocomplete( "option", "disabled", true );
    
option( options ) jQuery (plugin only) Sets one or more options for the autocomplete.
  • options
    Type: Object
    Description: The option-value pairs to set.

Code example:

Invoke the method:

$( ".selector" ).autocomplete( "option", { disabled: true } );
    
widget() jQuery Returns anjQueryobject containing the menu element.
  • This method does not accept any arguments.

Code example:

Invoke the widget method:

$( ".selector" ).autocomplete( "widget" );
    

Extension Points Returns Description
The Autocomplete Widget is created through theWidget Factoryand can be extended. When extending the widget, you can override or add behaviors to the extension widget. The methods provided below serve as extension points and have the same API stability as theplugin methodslisted above. For more information on widget extensions, seeExtending Widgets with the Widget Factory.
_renderItem( ul, item ) jQuery Method that controls the creation of each option in the widget's menu. The method must create a new <li> element, append it to the menu, and return it.

Note: At this time the<ul> element created must contain an <a> element for compatibility with the menu widget. See the example below.

  • ul
    Type: jQuery
    Description: The newly created<li>element must be appended to the<ul>element.
  • item
    Type: Object
    • label
      Type: String
      Description: The string to display for the entry.
    • item
      Type: String
      Description: The value inserted into the input when the entry is selected.

Code example:

Add the entry's value as<li>a data attribute on

_renderItem: function( ul, item ) {
  return $( "<li>" )
    .attr( "data-value", item.value )
    .append( $( "<a>" ).text( item.label ) )
    .appendTo( ul );
}
    
_renderMenu( ul, items ) jQuery (plugin only) This method is responsible for adjusting the menu size before the menu is displayed. The menu element can be obtained bythis.menu.elementusing.
  • ul
    Type: jQuery
    Description: An empty<ul>element to be used as the widget's menu.
  • items
    Type: Array
    Description: An array of items that match the user's input. Each item is an object with alabelandvalueproperty.

Code example:

Add a CSS class name to the old menu items.

_renderMenu: function( ul, items ) {
  var that = this;
  $.each( items, function( index, item ) {
    that._renderItemData( ul, item );
  });
  $( ul ).find( "li:odd" ).addClass( "odd" );
}
    
_resizeMenu() jQuery (plugin only) This method is responsible for adjusting the menu size before the menu is displayed. The menu element can be obtained bythis.menu.elementusing.
  • This method does not accept any arguments.

Code example:

The menu is always displayed as 500 pixels wide.

_resizeMenu: function() {
  this.menu.element.outerWidth( 500 );
}
    

Events Type Description
change( event, ui ) autocompletechange Triggered when the value of the input field changes.
  • event
    Type: Event
  • ui
    Type: Object
    • item
      Type: Object
      Description: The item selected from the menu, otherwise the property isnull。

Code example:

Initialize the autocomplete with the specified change callback:

$( ".selector" ).autocomplete({
  change: function( event, ui ) {}
});
    

Bind an event listener to the autocompletechange event:

$( ".selector" ).on( "autocompletechange", function( event, ui ) {} );
    
close( event, ui ) autocompleteclose Triggered when the menu is hidden. Not everycloseevent is accompanied by anchangeevent.
  • event
    Type: Event
  • ui
    Type: Object

Note:uiThe object is empty; it is included for consistency with other events.

Code example:

Initialize the autocomplete with the specified close callback:

$( ".selector" ).autocomplete({
  close: function( event, ui ) {}
});
    

Bind an event listener to the autocompleteclose event:

$( ".selector" ).on( "autocompleteclose", function( event, ui ) {} );
    
create( event, ui ) autocompletecreate Triggered when the autocomplete is created.
  • event
    Type: Event
  • ui
    Type: Object

Note:uiThe object is empty; it is included for consistency with other events.

Code example:

Initialize the autocomplete with the specified create callback:

$( ".selector" ).autocomplete({
  create: function( event, ui ) {}
});
    

Bind an event listener to the autocompletecreate event:

$( ".selector" ).on( "autocompletecreate", function( event, ui ) {} );
    
focus( event, ui ) autocompletefocus Triggered when focus moves to an item (not selected). The default action is to replace the value in the text field with the value of the focused item, even if the event is triggered by keyboard interaction. Canceling this event prevents the value from being updated, but does not prevent the menu item from gaining focus.
  • event
    Type: Event
  • ui
    Type: Object
    • item
      Type: Object
      Description: The item that gained focus.

Code example:

Initialize the autocomplete with the specified focus callback:

$( ".selector" ).autocomplete({
  focus: function( event, ui ) {}
});
    

Bind an event listener to the autocompletefocus event:

$( ".selector" ).on( "autocompletefocus", function( event, ui ) {} );
    
open( event, ui ) autocompleteopen Triggered when the suggestion menu is opened or updated.
  • event
    Type: Event
  • ui
    Type: Object

Note:uiThe object is empty; it is included for consistency with other events.

Code example:

Initialize the autocomplete with the specified open callback:

$( ".selector" ).autocomplete({
  open: function( event, ui ) {}
});
    

Bind an event listener to the autocompleteopen event:

$( ".selector" ).on( "autocompleteopen", function( event, ui ) {} );
    
response( event, ui ) autocompleteresponse Triggered after a search completes and before the menu is shown. Useful for local manipulation of suggestion data, where a customsourceoption callback is not required. This event is always triggered when the search completes, and it is triggered even if the menu is not shown because the search returned no results or Autocomplete is disabled.
  • event
    Type: Event
  • ui
    Type: Object
    • content
      Type: Array
      Description: Contains the response data and can be modified to change the displayed results. This data is already normalized, so if you modify the data, make sure each item contains thevalueandlabelproperty.

Code examples:

Initialize autocomplete with the specified response callback:

$( ".selector" ).autocomplete({
  response: function( event, ui ) {}
});
    

Bind an event listener to the autocompleteresponse event:

$( ".selector" ).on( "autocompleteresponse", function( event, ui ) {} );
    
select( event, ui ) autocompleteselect Triggered when an item is selected from the menu. The default action is to replace the value in the text field with the value of the selected item. Canceling this event prevents the value from being updated, but does not prevent the menu from closing.
  • event
    Type: Event
  • ui
    Type: Object
    • item
      Type: Object
      Description: An object with the selected item'slabelandvalueproperties.

Code examples:

Initialize autocomplete with the specified select callback:

$( ".selector" ).autocomplete({
  select: function( event, ui ) {}
});
    

Bind an event listener to the autocompleteselect event:

$( ".selector" ).on( "autocompleteselect", function( event, ui ) {} );
    

Examples

Example 1:

A simple jQuery UI Autocomplete.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>自动完成部件(Autocomplete Widget)演示</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
  <script src="//code.jquery.com/jquery-1.10.2.js"></script>
  <script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
</head>
<body>
 
<label for="autocomplete">选择一个编程语言:</label>
<input id="autocomplete">
 
<script>
$( "#autocomplete" ).autocomplete({
  source: [ "c++", "java", "php", "coldfusion", "javascript", "asp", "ruby" ]
});
</script>
 
</body>
</html>

Example 2:

Use a custom source callback to match the beginning of the term.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>自动完成部件(Autocomplete Widget)演示</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
  <script src="//code.jquery.com/jquery-1.10.2.js"></script>
  <script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
</head>
<body>
 
<label for="autocomplete">选择一个编程语言:</label>
<input id="autocomplete">
 
<script>
var tags = [ "c++", "java", "php", "coldfusion", "javascript", "asp", "ruby" ];
$( "#autocomplete" ).autocomplete({
  source: function( request, response ) {
          var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( request.term ), "i" );
          response( $.grep( tags, function( item ){
              return matcher.test( item );
          }) );
      }
});
</script>
 
</body>
</html>

Other extensions