Панель Управления


Видеокурс: "Javascript+jQuery для начинающих в видеоформате" Проверка времени и определение часового пояса рабочей станции. RU-CENTER. Центр регистрации доменов зоны .RU Сейчас выгодная возможность зарегистрировать домен .РФ в RU-CENTER Информационная безопасность Система интернет-расчетов RUpay Графический редактор ГИМП (GIMP) Зинаида Лукьянова. Видеокурс Фотошоп с нуля. Евгений Попов. Видеокурс HTML + PHP + MySQL. Весь Софт Софтодром "Электрошоп". Поиск электронных товаров. Джава. Ява. Java. Дмитрий Котеров, Алексей Костарев. PHP-5. Наиболее полное руководство. 2-е издание.



Элемент Автозаполнение (Autocomplete) плагина UI библиотеки jQuery
Плагин UI версии 1.9.2 библиотеки jQuery версии 1.8.3 Сделано в kocby.ru Элемент Автозаполнение (Autocomplete) плагина UI библиотеки jQuery. Просто фокусируясь на поле с автозаполнением или вводя в это поле какие-то данные мы заставляем плагин Автозаполнение искать строки соответствующие текущему вводу и выдавать лист со списком значений для выбора из него. Вводя дополнительные буквы пользователь может уточнять фильтрацию, делать список более соответствующим его пожеланиям. Можно использовать предыдущий выбор значений, например, заголовки статей или емейл адресов из адресной книги. Автозаполнение можно использовать для связанной информации, например, исходя из введенного названия города выдавать его почтовый индекс и т.д. Для источника данных можно использовать локальное или удаленное хранилище. Локальное удобно для небольшие массивов данных (например, адресная книга с 50-тью записями). Удаленное хранилище следует использовать для больших баз банных, когда выборка может достигать тысячи и более вариантов.
© Перепечатка разрешается с установкой ссылки на ресурс http://kocby.ru
Autocomplete :: Автозаполнение
Описание: Автозаполнение дает возможность пользователям быстро находить и выбирать из заранее подготовленного списка значения, исходя из символов, которые они вводят. Автозаполнение делает более удобными и быстрыми поиск и фильтрацию.
Description: Autocomplete enables users to quickly find and select from a pre-populated list of values as they type, leveraging searching and filtering.

Пример странички с Автозаполнением дефолтным (по умолчанию):
$( ".selector" ).autocomplete({ source: availableTags });
можно посмотреть здесь.

Пример странички Автозаполнения с удаленным источником данных:
можно посмотреть здесь.

Пример странички Автозаполнение - удаленный источник данных с кэшированием:
можно посмотреть здесь.

Пример странички Автозаполнение - удаленный источник данных JSONP:
можно посмотреть здесь.

Пример странички Автозаполнение с возможностью перемещения по длинному списку с результатами, используя скроллинг.:
можно посмотреть здесь.

Пример странички Автозаполнение Комбобокс:
можно посмотреть здесь.

Пример странички Автозаполнение Адаптируй и Показывай:
можно посмотреть здесь.

Пример странички Автозаполнение парсинг данных в формате XML:
можно посмотреть здесь.

Пример странички Автозаполнение Категории:
можно посмотреть здесь.

Пример странички Автозаполнение Коррекция Акцента:
можно посмотреть здесь.

Пример странички Автозаполнение Множество значений:
можно посмотреть здесь.

Пример странички Автозаполнение Множество значений, удаленно:
можно посмотреть здесь.




Теория

Тесты по теории можно посмотреть здесь.




Options (Опции)



appendTo
Type: Selector
Default: "body"


Which element the menu should be appended to. Override this when the autocomplete is inside a position: fixed element. Otherwise the popup menu would still scroll with the page.

Code examples: (Примеры кода: )
Initialize the autocomplete with the appendTo option specified:
Инициализация Автозаполнения с определенной опцией appendTo:

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


Get or set the appendTo option, after initialization:
Можно получить или установить опцию appendTo после инициализации:

// getter
var appendTo = $( ".selector" ).autocomplete( "option", "appendTo" );
 
// setter
$( ".selector" ).autocomplete( "option", "appendTo", "#someElem" );



autoFocus
Type: Boolean
Default: false


If set to true the first item will automatically be focused when the menu is shown.
Если установлено на значение true, то при показе меню первый пункт автоматически фокусируется.

Code examples: (Примеры кода: )
Initialize the autocomplete with the autoFocus option specified:
Инициализация Автозаполнения с определенной опцией autoFocus:

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


Get or set the autoFocus option, after initialization:
Можно получить или установить опцию autoFocus после инициализации:

// getter
var autoFocus = $( ".selector" ).autocomplete( "option", "autoFocus" );
 
// setter
$( ".selector" ).autocomplete( "option", "autoFocus", true );



delay
Type: Integer
Default: 300


The delay in milliseconds between when a keystroke occurs and when a search is performed. A zero-delay makes sense for local data (more responsive), but can produce a lot of load for remote data, while being less responsive.
Задержка в миллисекундах между набором значения и формированием поиска. Нулевая задержка имеет смысл для локальных хранилищей информации (быстрый и точный ответ), но для удаленного хранилища нулевая задержка не так хороша, т.к. приводит к долгой загрузке малосоответствующих предложений.

Code examples: (Примеры кода: )
Initialize the autocomplete with the delay option specified:
Инициализация Автозаполнения с определенной опцией delay:

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


Get or set the delay option, after initialization:
Можно получить или установить опцию delay после инициализации:

// getter
var delay = $( ".selector" ).autocomplete( "option", "delay" );
 
// setter
$( ".selector" ).autocomplete( "option", "delay", 500 );



disabled
Type: Boolean
Default: false


Disables the autocomplete if set to true.
Отменяет Автозаполнение, если установлена на значение true.

Code examples: (Примеры кода: )
Initialize the autocomplete with the disabled option specified:
Инициализация Автозаполнения с определенной опцией disabled:

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


Get or set the disabled option, after initialization:
Можно получить или установить опцию disabled после инициализации:

// getter
var disabled = $( ".selector" ).autocomplete( "option", "disabled" );
 
// setter
$( ".selector" ).autocomplete( "option", "disabled", true );



minLength
Type: Integer
Default: 1


The minimum number of characters a user must type before a search is performed. Zero is useful for local data with just a few items, but a higher value should be used when a single character search could match a few thousand items.
Минимальное количество символов, которое пользователь должен внести для формирования Автозаполнения. Значение 0 (ноль) удобно для локальных небольших источников данных. В случае больших массивов данных (несколько тысяч и более) лучше использовать значения больше 1.

Code examples: (Примеры кода: )
Initialize the autocomplete with the minLength option specified:
Инициализация Автозаполнения с определенной опцией minLength:

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


Get or set the minLength option, after initialization:
Можно получить или установить опцию minLength после инициализации:

// getter
var minLength = $( ".selector" ).autocomplete( "option", "minLength" );
 
// setter
$( ".selector" ).autocomplete( "option", "minLength", 0 );



position
Type: Object
Default: { my: "left top", at: "left bottom", collision: "none" }


Identifies the position of the suggestions menu in relation to the associated input element. The of option defaults to the input element, but you can specify another element to position against. You can refer to the jQuery UI Position utility for more details about the various options.
Определяет позицию меню с предложениями относительно связанного с процессом ввода элемента input. По умолчанию опция of работает относительно элемента ввода, но можно определить другой элемент дома, относительно которого будет осуществляться позиционирование.

Code examples: (Примеры кода: )
Initialize the autocomplete with the position option specified:
Инициализация Автозаполнения с определенной опцией position:

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


Get or set the position option, after initialization:
Можно получить или установить опцию position после инициализации:

// getter
var position = $( ".selector" ).autocomplete( "option", "position" );
 
// setter
$( ".selector" ).autocomplete( "option", "position", { my : "right top", at: "right bottom" } );



source
Type: Array or String or Function( Object request, Function response( Object data ) )
Default: none; must be specified


Defines the data to use, must be specified.
Independent of the variant 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' html extension. The demos all focus on different variations of the source option - look for one that matches your use case, and check out the code.
Определяет данные для Автозаполнения. Обязательный реквизит.

Multiple types supported:
• Array: An array can be used for local data. There are two supported formats:
◦ An array of strings: [ "Choice1", "Choice2" ]
◦ An array of objects with label and value properties: [ { label: "Choice1", value: "value1" }, ... ]

The label property is displayed in the suggestion menu. The value will be inserted into the input element when a user selects an item. If just one property is specified, it will be used for both, e.g., if you provide only value properties, the value will also be used as the label.

• String: When a string is used, the Autocomplete plugin expects that string to point to a URL resource that will return JSON data. It can be on the same host or on a different one (must provide JSONP). The Autocomplete plugin does not filter the results, instead a query string is added with a term field, which the server-side script should use for filtering the results. For example, if the source option is set to "http://example.com" and the user types foo, a GET request would be made to http://example.com?term=foo. The data itself can be in the same format as the local data described above.

• Function: The third variation, a callback, provides the most flexibility and can be used to connect any data source to Autocomplete. The callback gets two arguments:
◦ A request object, with a single term property, which refers to the value currently in the text input. For example, if the user enters "new yo" in a city field, the Autocomplete term will equal "new yo".
◦ A response callback, which expects a single argument: the data to suggest to the user. This data should be filtered based on the provided term, and can be in any of the formats described above for simple local data. It's important when providing a custom source callback to handle errors during the request. You must always call the response callback even if you encounter an error. This ensures that the widget always has the correct state.

When filtering data locally, you can make use of the built-in $.ui.autocomplete.escapeRegex function. It'll take a single string argument and escape all regex characters, making the result safe to pass to new RegExp().

Code examples: (Примеры кода: )
Initialize the autocomplete with the source option specified:
Инициализация Автозаполнения с определенной опцией source:

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


Get or set the source option, after initialization:
Можно получить или установить опцию source после инициализации:

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



Methods (Методы)



close()
Closes the Autocomplete menu. Useful in combination with the search method, to close the open menu.
• This method does not accept any arguments.

Code examples: (Примеры кода: )
Invoke the close method:
Запуск метода close (закрыть):
$( ".selector" ).autocomplete( "close" );



destroy()
Removes the autocomplete functionality completely. This will return the element back to its pre-init state.
• This method does not accept any arguments.

Code examples: (Примеры кода: )
Invoke the destroy method:
Запуск метода destroy (разрушить):
$( ".selector" ).autocomplete( "destroy" );



disable()
Disables the autocomplete.
• This method does not accept any arguments.

Code examples: (Примеры кода: )
Invoke the disable method:
Запуск метода disable (выключить):
$( ".selector" ).autocomplete( "disable" );



enable()
Enables the autocomplete.
• This method does not accept any arguments.

Code examples: (Примеры кода: )
Invoke the enable method:
Запуск метода enable (включить):


option( optionName )
Returns: Object
Gets the value currently associated with the specified optionName.
• optionName
Type: String
The name of the option to get.

Code examples: (Примеры кода: )
Invoke the method:
Запуск метода:
var isDisabled = $( ".selector" ).autocomplete( "option", "disabled" );



option()
Returns: PlainObject
Gets an object containing key/value pairs representing the current autocomplete options hash.
• This method does not accept any arguments.

Code examples: (Примеры кода: )
Invoke the method:
Запуск метода:
var options = $( ".selector" ).autocomplete( "option" );



option( optionName, value )
Sets the value of the autocomplete option associated with the specified optionName.

• optionName
Type: String
The name of the option to set.

• value
Type: Object
A value to set for the option.

Code examples: (Примеры кода: )
Invoke the method:
Запуск метода:
$( ".selector" ).autocomplete( "option", "disabled", true );



option( options )
Sets one or more options for the autocomplete.

• options
Type: Object
A map of option-value pairs to set.

Code examples: (Примеры кода: )
Invoke the method:
Запуск метода:
$( ".selector" ).autocomplete( "option", { disabled: true } );



search( [value ] )
Triggers a search event and invokes the data source if the event is not canceled. Can be used by a selectbox-like button to open the suggestions when clicked. When invoked with no parameters, the current input's value is used. Can be called with an empty string and minLength: 0 to display all items.

• value
Type: String

Code examples: (Примеры кода: )
Invoke the method:
Запуск метода:
$( ".selector" ).autocomplete( "search", "" );



widget()
Returns a jQuery object containing the menu element. Although the menu items are constantly created and destroyed, the menu element itself is created during initialization and is constantly reused. • This method does not accept any arguments.

Code examples: (Примеры кода: )
Invoke the widget method:
Запуск метода виджета:
$( ".selector" ).autocomplete( "widget" );



Events (События)



change( event, ui )
Type: autocompletechange

Triggered when the field is blurred, if the value has changed.

• event
Type: Event

• ui
Type: Object
◦ item
Type: jQuery
The item selected from the menu, if any. Otherwise the property is null.

Code examples: (Примеры кода: )
Initialize the autocomplete with the change callback specified:
$( ".selector" ).autocomplete({
    change: function( event, ui ) {}
});


Bind an event listener to the autocompletechange event:
$( ".selector" ).on( "autocompletechange", function( event, ui ) {} );



close( event, ui )
Type: autocompleteclose

Triggered when the menu is hidden. Not every close event will be accompanied by a change event.

• event
Type: Event

• ui
Type: Object

Code examples: (Примеры кода: )
Initialize the autocomplete with the close callback specified:
$( ".selector" ).autocomplete({
    close: function( event, ui ) {}
});


Bind an event listener to the autocompleteclose event:
$( ".selector" ).on( "autocompleteclose", function( event, ui ) {} );



create( event, ui )
Type: autocompletecreate

Triggered when the autocomplete is created.

• event
Type: Event

• ui
Type: Object

Code examples: (Примеры кода: )
Initialize the autocomplete with the create callback specified:
$( ".selector" ).autocomplete({
    create: function( event, ui ) {}
});


Bind an event listener to the autocompletecreate event:
$( ".selector" ).on( "autocompletecreate", function( event, ui ) {} );



focus( event, ui )
Type: autocompletefocus

Triggered when focus is moved to an item (not selecting). The default action is to replace the text field's value with the value of the focused item, though only if the event was triggered by a keyboard interaction.
Canceling this event prevents the value from being updated, but does not prevent the menu item from being focused.

• event
Type: Event

• ui
Type: Object

◦ item
Type: jQuery
The focused item.

Code examples: (Примеры кода: )
Initialize the autocomplete with the focus callback specified:
$( ".selector" ).autocomplete({
    focus: function( event, ui ) {}
});


Bind an event listener to the autocompletefocus event:
$( ".selector" ).on( "autocompletefocus", function( event, ui ) {} );



open( event, ui )
Type: autocompleteopen

Triggered when the suggestion menu is opened or updated.

• event
Type: Event

• ui
Type: Object

Code examples: (Примеры кода: )
Initialize the autocomplete with the open callback specified:
$( ".selector" ).autocomplete({
    open: function( event, ui ) {}
});


Bind an event listener to the autocompleteopen event:
$( ".selector" ).on( "autocompleteopen", function( event, ui ) {} );



response( event, ui )
Type: autocompleteresponse

Triggered after a search completes, before the menu is shown. Useful for local manipulation of suggestion data, where a custom source option callback is not required. This event is always triggered when a search completes, even if the menu will not be shown because there are no results or the Autocomplete is disabled.

• event
Type: Event

• ui
Type: Object
◦ content

Type: Array

Contains the response data and can be modified to change the results that will be shown. This data is already normalized, so if you modify the data, make sure to include both value and label properties for each item.

Code examples: (Примеры кода: )
Initialize the autocomplete with the response callback specified:
$( ".selector" ).autocomplete({
    response: function( event, ui ) {}
});


Bind an event listener to the autocompleteresponse event:
$( ".selector" ).on( "autocompleteresponse", function( event, ui ) {} );



search( event, ui )
Type: autocompletesearch

Triggered before a search is performed, after minLength and delay are met. If canceled, then no request will be started and no items suggested.

• event
Type: Event

• ui
Type: Object

Code examples: (Примеры кода: )
Initialize the autocomplete with the search callback specified:
$( ".selector" ).autocomplete({
    search: function( event, ui ) {}
});


Bind an event listener to the autocompletesearch event:
$( ".selector" ).on( "autocompletesearch", function( event, ui ) {} );



select( event, ui )
Type: autocompleteselect

Triggered when an item is selected from the menu. The default action is to replace the text field's value 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: jQuery
The selected item.

Code examples: (Примеры кода: )
Initialize the autocomplete with the select callback specified:
$( ".selector" ).autocomplete({
    select: function( event, ui ) {}
});


Bind an event listener to the autocompleteselect event:
$( ".selector" ).on( "autocompleteselect", function( event, ui ) {} );



Overview (Обзор)
By giving an Autocomplete field focus or entering something into it, the plugin starts searching for entries that match and displays a list of values to choose from. By entering more characters, the user can filter down the list to better matches.

This can be used to choose previously selected values, such as entering tags for articles or entering email addresses from an address book. Autocomplete can also be used to populate associated information, such as entering a city name and getting the zip code.

You can pull data in from a local or remote source: Local is good for small data sets, e.g., an address book with 50 entries; remote is necessary for big data sets, such as a database with hundreds or millions of entries to select from. To find out more about customizing the data soure, see the documentation for the source option.

Просто фокусируясь на поле с автозаполнением или вводя в это поле какие-то данные мы заставляем плагин Автозаполнение искать строки соответствующие текущему вводу и выдавать лист со списком значений для выбора из него. Вводя дополнительные буквы пользователь может уточнять фильтрацию, делать список более соответствующим его пожеланиям.

Можно использовать предыдущий выбор значений, например, заголовки статей или емейл адресов из адресной книги. Автозаполнение можно использовать для связанной информации, например, исходя из введенного названия города выдавать его почтовый индекс и т.д.

Для источника данных можно использовать локальное или удаленное хранилище. Локальное удобно для небольшие массивов данных (например, адресная книга с 50-тью записями). Удаленное хранилище следует использовать для больших баз банных, когда выборка может достигать тысячи и более вариантов.


Keyboard interaction (Клавиатура, горячие клавиши)
When the menu is open, the following key commands are available:
• UP - Move focus to the previous item. If on first item, move focus to the input. If on the input, move focus to last item.
• DOWN - Move focus to the next item. If on 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 through a page of items (based on height of menu). It's generally a bad idea to display so many items that users need to page..

When the menu is closed, the following key commands are available:
• UP/DOWN - Open the menu, if the minLength has been met.

Когда фокус на хидере, возможны следующие команды с клавиатуры:
• UP - Перемещает фокус на предыдущий пункт. Если текущий пункт первый, перемещает фокус на последний пункт.
• DOWN - Перемещает фокус на следующий пункт. Если текущий пункт последний, перемещает фокус на первый пункт.
• ESCAPE - Закрывает меню.
• ENTER - Производит выбор текущего пункта и закрывает меню.
• TAB - Производит выбор текущего пункта, закрывает меню, перемещает фокус на следующий элемент.
• PAGE UP/DOWN - Пролистывает список пунктов (зависит от высоты меню). В общем не очень хорошая мысль - показывать слишком много пунктов для выбора.

Когда меню закрыто, возможны следующие команды:
• UP/DOWN - Открывает меню при условии соблюдения требований по значению опции minLength.


Additional Notes (Дополнительная информация)
• This widget requires some functional CSS, otherwise it won't work. If you build a custom theme, use the widget's specific CSS file as a starting point.
• Этот виджет требует определенных стилей CSS, иначе он не будет работать. Если вы используете адаптированную схему, оттолкитесь в своей разработке от специализированного файла CSS.


Examples: (Примеры: )



Example: A simple jQuery UI Autocomplete
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>autocomplete demo</title>
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css">
    <script src="http://code.jquery.com/jquery-1.8.2.js"></script>
    <script src="http://code.jquery.com/ui/1.9.1/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>
Этот пример можно посмотреть здесь.


Example: Using a custom source callback to match only the beginning of terms
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>autocomplete demo</title>
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css">
    <script src="http://code.jquery.com/jquery-1.8.2.js"></script>
    <script src="http://code.jquery.com/ui/1.9.1/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>
Этот пример можно посмотреть здесь.


Примеры автозаполнения на этом сайте: Дефолтное, Из дальнего далека, Кэшируемое, Источник JSONP, Скроллинговое, Комбобокс, Адаптируемое, Парсинг XML, Категории, Иностранное, Множественное, Много издалека.



Если вы планируете вернуться сюда позднее...
Пожалуйста, запомните эту страничку -
URL: http://kocby.ru/post/webmaster/jquery/ui/autocomplete/
Спасибо за посещение этой странички и внимательное отношение к ее контенту и дизайну. Удачи и успеха!
© KOCBY.RU :: перепечатка материалов разрешается с указанием ссылки на домен KOCBY.RU ©
Basket is empty :: Корзина пустая
Close and hide in basket :: Закрыть и спрятать в корзину
Посмотри в зеркало! Что там видно?
Красивая девушка брюнетка слева Красивая девушка блондинка справа




Close and hide in basket :: Закрыть и спрятать в корзину статистическую информацию о посетителях Клуба.
Створки зеркала Клуба Одиноких Сердец.
Красивая девушка блондинка слева Красивая девушка брюнетка справа