jQuery UI API - Autocomplete Widget
Categories
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 native
changeevent.
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, Code examples: Initialize an autocomplete with the specified
$( ".selector" ).autocomplete({ appendTo: "#someElem" });
After initialization, get or set the // 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 specified
$( ".selector" ).autocomplete({ autoFocus: true });
After initialization, get or set the // 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 specified
$( ".selector" ).autocomplete({ delay: 500 });
After initialization, get or set the // 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 specified
$( ".selector" ).autocomplete({ disabled: true });
After initialization, get or set the // 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 specified
$( ".selector" ).autocomplete({ minLength: 0 });
After initialization, get or set the // 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 specified
$( ".selector" ).autocomplete({ position: { my : "right top", at: "right bottom" } });
After initialization, get or set the
// 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 on Multiple types are supported:
Code example: Initialize the autocomplete with the specified
$( ".selector" ).autocomplete({ source: [ "c++", "java", "php", "coldfusion", "javascript", "asp", "ruby" ] });
After initialization, get or set the // 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.
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.
Code example: Invoke the destroy method: $( ".selector" ).autocomplete( "destroy" ); |
| disable() | jQuery (plugin only) | Disable the autocomplete.
Code example: Invoke the disable method: $( ".selector" ).autocomplete( "disable" ); |
| enable() | jQuery (plugin only) | Enable the autocomplete.
Code example: Invoke the enable method: $( ".selector" ).autocomplete( "enable" ); |
| option( optionName ) | Object | Gets the value currently associated with the specifiedoptionNameoption.
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.
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.
Code example: Invoke the method: $( ".selector" ).autocomplete( "option", "disabled", true ); |
| option( options ) | jQuery (plugin only) | Sets one or more options for the autocomplete.
Code example: Invoke the method:
$( ".selector" ).autocomplete( "option", { disabled: true } );
|
| search( [value ] ) | jQuery (plugin only) | Triggers thesearchsearch event, and if the event is not canceled, invokes the data source. When clicked, can be used by a selectbox-like button to open the suggestions. When invoked with no arguments, the current input value is used. Can be invoked with an empty string andminLength: 0to display all items.
Code example: Invoke the search method: $( ".selector" ).autocomplete( "search", "" ); |
| widget() | jQuery | Returns anjQueryobject containing the menu element.
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
Code example: Add the entry's value as
_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.
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.
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.
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.
Note: 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.
Note: 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.
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.
Note: 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.
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 ) {} );
|
| search( event, ui ) | autocompletesearch | Met before the search is executedminLengthanddelayand then triggered. If this event is canceled, no request will be submitted and no suggestion entries will be provided.
Note: Code examples: Initialize autocomplete with the specified search callback:
$( ".selector" ).autocomplete({
search: function( event, ui ) {}
});
Bind an event listener to the autocompletesearch event:
$( ".selector" ).on( "autocompletesearch", 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.
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