Easy Tutorial
❮ Api Switchclass Api Disableselection ❯

jQuery UI API - Autocomplete Widget

Category

Widgets

Usage

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

Version Added: 1.8

Any field that can receive input can be turned into an Autocomplete, i.e., <input> elements, <textarea> elements, and elements with the contenteditable attribute.

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

This widget can be used to select previously chosen values, such as entering article tags or inputting email addresses from an address book. Autocomplete can also be used to fill related information, such as entering a city name to get the city's postal code.

You can fetch data from local or remote sources: local sources are suitable for small datasets, e.g., an address book with 50 entries; remote sources are suitable for large datasets, such as a database with hundreds or thousands of entries. For more information on custom data sources, see the documentation for the source option.

Keyboard Interaction

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

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

Theming

The Autocomplete Widget uses the jQuery UI CSS Framework to define its appearance and style. To use the styles specific to the Autocomplete Widget, you can use the following CSS class names:

Dependencies

Additional Notes

Quick Navigation

Options Methods Extension Points Events
appendTo autoFocus delay disabled minLength position source close destroy disable enable option search widget _renderItem _renderMenu _resizeMenu change close create focus open response search select
Options Type Description Default Value
appendTo Selector The element to which the menu should be appended. When this value is null, the parent element of the input field will be checked for the ui-front class. If an element with the ui-front class is found, the menu will be appended to that element. If no element with the ui-front class is found, regardless of the value, the menu will be appended to the body.

Note: The appendTo option should not be changed while the suggestion menu is open.
Code example: Initialize autocomplete with a specified appendTo option:
$(".selector").autocomplete({ appendTo: "#someElem" });
After initialization, get or set the appendTo option:
// getter
var appendTo = $(".selector").autocomplete("option", "appendTo");
// setter
$(".selector").autocomplete("option", "appendTo", "#someElem"); | null |

| autoFocus | Boolean | If set to true, the first item will automatically be focused when the menu is shown.
Code example: Initialize autocomplete with a specified autoFocus option:
$(".selector").autocomplete({ autoFocus: true });
After initialization, get or set the autoFocus option:
// getter
var autoFocus = $(".selector").autocomplete("option", "autoFocus");
// setter
$(".selector").autocomplete("option", "autoFocus", true); | false |

| delay | Integer | The delay in milliseconds between pressing a key and performing the search. Zero delay makes sense for local data (more responsive), but can produce a lot of load for remote data, while also being less responsive.
Code example: Initialize autocomplete with a specified delay option:
$(".selector").autocomplete({ delay: 500 });
After initialization, get or set the delay option:
// getter
var delay = $(".selector").autocomplete("option", "delay");
// setter
$(".selector").autocomplete("option", "delay", 500); | 300 |

| disabled | Boolean | If set to true, the autocomplete is disabled.
Code example: Initialize autocomplete with a specified disabled option:
$(".selector").autocomplete({ disabled: true });
After initialization, get or set the disabled option:
// getter
var disabled = $(".selector").autocomplete("option", "disabled");
// setter
$(".selector").autocomplete("option", "disabled", true); | false |

| minLength | Integer | The minimum number of characters a user must type before a search is performed. For local data with only a few items, it usually makes sense to set this to zero, but a higher value is necessary when a single character search could match thousands of items.
Code example: Initialize autocomplete with a specified minLength option:
$(".selector").autocomplete({ minLength: 0 });
After initialization, get or set the minLength option:
// getter
var minLength = $(".selector").autocomplete("option", "minLength");
// setter
$(".selector").autocomplete("option", "minLength", 0); | 1 | The position option suggests the menu's location in relation to the associated input element. The default option is the input element, but you can specify another positioning element. For more details on various options, please refer to jQuery UI Positioning (Position).
Code example: Initialize the autocomplete with specified position options:

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

After initialization, get or set the position option:

// 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 use, must be specified. <br> 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 use Scott González's HTML extension. The demo focuses on different variables of the source option - you can find the one that matches your use case and view the related code. Supports multiple types: <br> <br> Array: An array for local data. Supports two formats: <br> <br> String array: ["Choice1", "Choice2"] <br> Array of objects with label and value properties: [{ label: "Choice1", value: "value1" }, ...] <br> <br> The label property is displayed in the suggestion menu. When a user selects an entry, the value will be inserted into the input element. If only one property is specified, it will be treated as both label and value, for example, if you only provide the value property, the value will also be treated as the label. <br> <br> String: When using a string, the Autocomplete plugin expects the string to point to a URL resource that returns JSON data. It can be on the same host or a different host (must provide JSONP). The Autocomplete plugin does not filter results, but adds a query string with a term field for server-side scripts to filter results. For example, if the source option is set to "http://example.com" and the user types "foo", the GET request will be http://example.com?term=foo. The format of the data itself can be the same as the local data described earlier. <br> Function: The third variable, a callback function, offers the most flexibility, allowing any data source to be connected to Autocomplete. The callback function accepts two parameters: <br> <br> A request object, with a term property, representing the value in the current text input. For example, if the user types "new yo" in the city field, the Autocomplete term will be "new yo". <br> A response callback function, providing a single parameter: the data suggested to the user. This data should be filtered based on the provided term and can be in any format of the local data described earlier. Used to provide a custom source callback to handle errors during the request. Even if an error occurs, you must call the response callback function. This ensures the widget is always in the correct state. <br> <br> When filtering local data, you can use the built-in $.ui.autocomplete.escapeRegex function. It accepts a string parameter, escapes all regex characters, making the result safe to pass into new RegExp(). Code example: Initialize autocomplete with the specified source option: $( ".selector" ).autocomplete({ source: ["c++", "java", "php", "coldfusion", "javascript", "asp", "ruby"] }); After initialization, get or set the source option: // getter <br> var source = $( ".selector" ).autocomplete( "option", "source" ); <br> <br> // setter <br> $( ".selector" ).autocomplete( "option", "source", ["c++", "java", "php", "coldfusion", "javascript", "asp", "ruby"] ); | none; must be specified |

Method Returns Description
close() jQuery (plugin only) Closes the Autocomplete menu. When used in conjunction with the search method, it can be used to close the open menu. <br> This method does not accept any parameters. Code example: Call the close method: $( ".selector" ).autocomplete( "close" );
destroy() jQuery (plugin only) Completely removes the autocomplete functionality. This will return the element to its pre-init state. <br> This method does not accept any parameters. Code example: Call the destroy method: $( ".selector" ).autocomplete( "destroy" );
disable() jQuery (plugin only) Disables the autocomplete. <br> This method does not accept any parameters. Code example: Call the disable method: $( ".selector" ).autocomplete( "disable" );
enable() jQuery (plugin only) Enables the autocomplete. <br> This method does not accept any parameters. Code example: Call the enable method: $( ".selector" ).autocomplete( "enable" );
option( optionName ) Object Gets the value currently associated with the specified optionName. <br> optionName<br> Type: String<br> Description: The name of the option to get. Code example: Call the method: var isDisabled = $( ".selector" ).autocomplete( "option", "disabled" );
option() PlainObject Gets an object containing key/value pairs representing the current autocomplete options hash. <br> This method does not accept any parameters. Code example: Call the method: var options = $( ".selector" ).autocomplete( "option" );
option( optionName, value ) jQuery (plugin only) Sets the value of the autocomplete option associated with the specified optionName. <br> optionName<br> Type: String<br> Description: The name of the option to set.<br> value<br> Type: Object<br> Description: A value to set for the option. Code example: Call the method: $( ".selector" ).autocomplete( "option", "disabled", true );
option( options ) jQuery (plugin only) Sets one or more options for the autocomplete. <br> options<br> Type: Object<br> Description: A map of option-value pairs to set. Code example: Call the method: $( ".selector" ).autocomplete( "option", { disabled: true } );
search( [value ] ) jQuery (plugin only) Triggers the search event with minLength: 0 to display all items. <br> value<br> Type: String Code example: Call the search method: $( ".selector" ).autocomplete( "search", "" );
widget() jQuery Returns a jQuery object containing the menu element. Although the menu items are created and destroyed, the menu element itself is created once and reused. <br> This method does not accept any parameters. Code example: Call the widget method: $( ".selector" ).autocomplete( "widget" );
Extension Points Return Description
Autocomplete Widget extended through Widget Factory plugin methods extending widgets through 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. <br> Note: At this time, the <ul> element created must contain an <a> element for compatibility with the menu widget. See the example below. <br> ul<br> Type: jQuery<br> Description: The <ul> element to which the newly created <li> element must be appended. <br> <br> item<br> Type: Object<br> <br> label<br> Type: String<br> Description: The string to be displayed for the item. <br> <br> value<br> Type: String<br> Description: The value to be inserted into the input field when the item is selected. Example code: Add the item's value as a data attribute on the <li>. _renderItem: function( ul, item ) {<br> return $( "<li>" )<br> .attr( "data-value", item.value )<br> .append( $( "<a>" ).text( item.label ) )<br> .appendTo( ul );<br>}
_renderMenu( ul, items ) jQuery (plugin only) This method is responsible for adjusting the menu size before it is displayed. The menu element can be accessed via this.menu.element. <br> ul<br> Type: jQuery<br> Description: An empty <ul> element to be used as the widget's menu. <br> <br> items<br> Type: Array<br> Description: An array of items matching the user's input. Each item is an object with label and value properties. Example code: Add a CSS class name to old menu items. _renderMenu: function( ul, items ) {<br> var that = this;<br> $.each( items, function( index, item ) {<br> that._renderItemData( ul, item );<br> });<br> $( ul ).find( "li:odd" ).addClass( "odd" );<br>}
_resizeMenu() jQuery (plugin only) This method is responsible for adjusting the menu size before it is displayed. The menu element can be accessed via this.menu.element. <br> This method does not accept any parameters. Example code: The menu is always displayed at 500 pixels wide. _resizeMenu: function() {<br> this.menu.element.outerWidth( 500 );<br>}
Event Type Description
change( event, ui ) autocompletechange This event is triggered if the value of the input field changes. <br> event<br> Type: Event<br> <br> ui<br> Type: Object<br> <br> item<br> Type: Object<br> Description: The item selected from the menu, otherwise null. Example code: Initialize the autocomplete with a specified change callback: $( ".selector" ).autocomplete({<br> change: function( event, ui ) {}<br>}); 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 every close event is followed by a change event. <br> event<br> Type: Event<br> <br> ui<br> Type: Object Note: The ui object is empty, it is included here for consistency with other events. Code example: Initialize autocomplete with a specified close callback: $( ".selector" ).autocomplete({<br> close: function( event, ui ) {}<br>}); Bind an event listener to the autocompleteclose event: $( ".selector" ).on( "autocompleteclose", function( event, ui ) {} );
create( event, ui ) autocompletecreate Triggered when the autocomplete is created. <br> event<br> Type: Event<br> <br> ui<br> Type: Object Note: The ui object is empty, it is included here for consistency with other events. Code example: Initialize autocomplete with a specified create callback: $( ".selector" ).autocomplete({<br> create: function( event, ui ) {}<br>}); Bind an event listener to the autocompletecreate event: $( ".selector" ).on( "autocompletecreate", function( event, ui ) {} );
focus( event, ui ) autocompletefocus Triggered when the 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. <br> event<br> Type: Event<br> <br> ui<br> Type: Object<br> <br> item<br> Type: Object<br> Description: The item that gains focus. Code example: Initialize autocomplete with a specified focus callback: $( ".selector" ).autocomplete({<br> focus: function( event, ui ) {}<br>}); 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. <br> event<br> Type: Event<br> <br> ui<br> Type: Object Note: The ui object is empty, it is included here for consistency with other events. Code example: Initialize autocomplete with a specified open callback: $( ".selector" ).autocomplete({<br> open: function( event, ui ) {}<br>}); Bind an event listener to the autocompleteopen event: $( ".selector" ).on( "autocompleteopen", function( event, ui ) {} );
response(event, ui) autocompleteresponse Triggered after the search completes but before the menu is displayed. Used for local manipulation of suggestion data, where the custom source

event
Type: Event

ui
Type: Object

content
Type: Array
Description: Contains the response data, which can be modified to change the display results. The data is normalized, so if you want to modify it, ensure each item contains value and label properties. Code example: Initialize autocomplete with a 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 | Triggered before the search is executed, satisfying minLength and delay
event
Type: Event

ui
Type: Object
Note: The ui object is empty, including it here for consistency with other events. Code example: Initialize autocomplete with a 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 will prevent the value from being updated but will not prevent the menu from closing.
event
Type: Event

ui
Type: Object

item
Type: Object
Description: An object with the label and value properties of the selected item. Code example: Initialize autocomplete with a specified select callback:

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

Bind an event listener to the autocompleteselect event:

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

Example

A simple jQuery UI Autocomplete.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Autocomplete Widget Demo</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">Select a programming language:</label>
<input id="autocomplete">

<script>
$( "#autocomplete" ).autocomplete({
  source: [ "c++", "java", "php", "coldfusion", "javascript", "asp", "ruby" ]
});
</script>
</body>
</html>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Autocomplete Widget Demo</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">Select a programming language:</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>

View Demo

Using a custom source callback to match the beginning of conditions.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Autocomplete Widget Demo</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">Select a programming language:</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>

View Demo

❮ Api Switchclass Api Disableselection ❯