AutoCompleter (v1.0)
This AutoCompleter script for MooTools provides the functionality for text suggestion and completion.
It features different data-sources (local, JSON or XML), a variety of user interactions,
custom formatting, multiple selection, animations and much more.
Compatibility
Fully compatible with all A-Grade Browsers (Internet Explorer 6+, Opera 9, Firefox 1.5+ and Safari 2+)
Features
All classes extend the base class Autocompleter.Base, which provides all basic features to create an Autocompleter from any provided source. Both, Ajax.Json and Ajax.Json extend Autocompleter.Ajax.Base, which handles the query request and response.
How to use
Simple Example that uses a JSON source to create the Autocompleter
var searchInput = $('search-field'); // A simple spinner div, display-toggled during request var indicator = new Element('div', { 'class': 'autocompleter-loading', 'styles': {'display': 'none'} }).injectAfter(searchInput); // appended after the input var completer = new Autocompleter.Ajax.Json(searchInput, { 'url': '/search', 'postVar': 'q', 'onRequest': function(el) { indicator.setStyle('display', ''); }, 'onComplete': function(el) { indicator.setStyle('display', 'none'); } });
No inline XHTML is needed:
<input type="text" id="search-field"/>The reponse from the request is a simple JSON Array (example for query “aja”):
["aja","ajaba","ajabais","ajaban","ajabas","ajad","ajada","ajadas","ajado","ajados"]
Check the source of the showcases for more examples.
Download
Requirements
MooTools JavaScript Framework 1.1
Download MooTools 1.11 with at least these modules:
- Element.Event
- Element.Selectors
- Element.Form
- Element.Dimensions
- Fx.Style
- Ajax (for HTML requests)
- Json (for JSON requests)
- Window.DomReady (facultative)
Documentation
For additional documentation check the documented source code!
Base Options
- minLength: Number, default 1. Minimum length to start auto compliter
- useSelection: Boolean, default true. Select completed text part (works only for appended strings)
- markQuery: Boolean, default true. Mark queried string with @*@
- inheritWidth: Boolean, default true. Inherit width for the autocompleter overlay from the input field
- maxChoices: Number, default 10. Maximum of suggested fields.
- injectChoice: Function, optional. Callback for injecting the list element with the arguments (itemValue, itemIndex), take a look at updateChoices for default behaviour.
- onSelect: Event Function. Fires when when an item gets selected.
- onShow: Event Function. Fires when autocompleter list shows.
- onHide: Event Function. Fires when autocompleter list hides.
- customTarget: Element, optional. Allows to override the autocompleter list element with your own list element.
- className: String, default ‘autocompleter-choices’. Class name for the list element.
- zIndex: Number, default 42. z-Index for the list element.
- observerOptions: optional Options Object. For the Observer class.
- fxOptions: optional Options Object. For the Fx.Style on the list element.
Local Options
- minLength: Overrides minLength to 0.
- filterTokens: Function, optional. Allows to override default @filterTokens@ method
Ajax.Base Options
- postVar: String, default ‘value’. Post variable name for the query string
- postData: Object, optional. Additional request data
- ajaxOptions: optional Options Object. For the Ajax instance
- onRequest: Event Function. … same
- onComplete: Event Function. … same
Ajax.Json Options
No options now, use this one instead of Ajax.Xhtml to be one of the cool guys ;) . Parsing JSON is faster/shorter than writing and reading XHTML
Ajax.Xhtml Options
- parseChoices: Function, optional. Allows to override default parseChoices method
Observer Options
Documentation in the source code.
Changelog
- 1.1.2 (2008-08-19)
- Added: Option indicator for Autocompleter.Ajax, element is shown during request.
- Added: Option indicatorClass, class-name is added during request to input.
- Added: Option visibleChoices (default true), to scroll hidden choices into view
- Added: Option emptyChoices, called instead of hideChoices when tokens are empty.
- Fixed: Fixed filter loops on RegExp::test for Opera.
- Fixed: Element::getSelectedRange returns correct positions for textareas in IE.
- Fixed: Selected item resets correctly.
- Fixed: Update can now also handle tokens as Hash, length check fixed.
- Changed: BREAKING CHANGE (incl. Compatibility)! Naming conventions following MooTools 1.2
- Autocompleter.Base to Autocompleter
- Autocompleter.Ajax to Autocompleter.Request
- Autocompleter.Ajax.Json/Xhtml to Autocompleter.Request.JSON/HTML
- Changed: BREAKING CHANGE (incl. Compatibility)! Extracted Local and Request from Autocompleter.js
- Changed: Removed Element::getOffsetParent, included in MooTools 1.2
- Changed: Element::getCaretPosition renamed to Element::getSelectedRange
- Changed: Added JSON and HTML Request showcases.
- 1.1.1 (2008-04-27)
- Fixed: Removed orphaned trash events and added destroy for fix overlay.
- Fixed: Added missing addChoiceEvents call to default injectChoice in Autocompleter.Ajax.Xhtml to add mouse events.
- 1.1 (2008-03-28)
- Added: Support for tagging, multiple entries with configurable parsers (allowing commas, spaces …)
- Added: Option selectMode for different select behaviours
- Added: Option overflow for scrolling through more suggestions
- Added: Options filter, filterCase and filterSubset, for easier locale usage, better query marks and to prepare caching feature
- Added: Option autoSubmit to automatically submit the form on enter.
- Added: Option forceSelect to allow select-box behaviour
- Added: Option typeAhead for fast and simple suggestions (works best with forceSelect)
- Changed: Updated to MooTools 1.2 dev
- Changed: New Events for a better widget control
- Fixed: Selection behaviour works a lot better, also for tagging
- … and more fixes
- 1.0.4 (2007-05-23)
- Fixed: Fix for & that has the Event::code of key-up (only for keypress event)
- Changed: Added overflown option to the options object and more clean-up’s
- 1.0.3 (2007-05-20)
Official release with support for local, JSON and HTML responses
License
All files are © 2008-2009 by Harald Kirschner and available under the MIT License.
Contact & Discussion
For asking questions, requesting features, filing bugs or contributing other thoughts on this project use the support forum below. Before posting a new question, read through the documentation and the contributed notes for an answer. For problem reports make sure to add enough details like browser, version and a link or the relevant code.
You can contact me for non-support related notes.
Professional Support
I am available for hire if you look for professional and swift help. I can come to your rescue for installation, customization or extending the existing source for your needs.
261 Comments
Please use the support forums for discussing the project, asking questions or posting bug-fixes!
(i translitirate my tokens to latin names to get the images)
The code is bad but ain't work in Google Chrome :( it works in FF and IE at the same time! Please help me! How can i include image elements in the result list?
document.addEvent('domready', function() {
// функция транслитерации
function translit(s)
{
var t="аaбbвvгgдdеeёjoжzhзzиiйjjкkлlмmнnоoпpрrсsтtуuфfхkhцcчchшshщshhъ''ыyь'эehюjuяjaАAБBВVГGДDЕEЁJoЖZhЗZИIЙJjКKЛLМMНNОOПPРRСSТTУUФFХKhЦCЧChШShЩShhЪ''ЫYЬ'ЭEhЮJuЯJa";
t=t.replace(/([а-яёЁ])([a-z']+)/gi,'.replace(/$1/g,"$2")');
return eval("s"+t);
}
var tokens = ['Афганистан', 'Aвстралия', 'Албания', 'Алжир', 'Аргентина', 'Ангола', 'Аргентина', 'Армения', 'Аруба', 'Aзербайджан', 'Aвстрия', 'Багамы', 'Бахрейн', 'Бангладеш', 'Барбадос', 'Беларусь', 'Бельгия', 'Белиз', 'Бенин', 'Бермудские острова', 'Бутан', 'Боливия', 'Босния и Герцеговина', 'Ботсвана', 'Буве, остров', 'Бразилия', 'Бруней Дарассалам', 'Болгария', 'Буркина-Фасо', 'Бурунди', 'Бутан', 'Камерун', 'Канада', 'Каймановы о-ва (Великобритания)', 'Центрально-африканская Республика', 'Чад', 'Чили', 'Китай', 'Остров Рождества', 'Кокосовые (Килинг) острова', 'Колумбия', 'Коморские о-ва', 'Конго', 'Демократическая Республика Конго', 'Острова Кука (Новая Зеландия)', 'Коста-Рика', 'Кот-Дивуар', 'Хорватия', 'Куба', 'Кипр', 'Чехия', 'Дания', 'Джибути', 'Доминиканская республика', 'Эквадор', 'Египет', 'Экваториальная Гвинея', 'Эритрия', 'Эстония', 'Эфиопия', 'Фолклендские (Мальвинские) острова', 'Фарерские острова', 'Фиджи', 'Финляндия', 'Франция', 'Французская Гвиана', 'Французская Полинезия', 'Габон', 'Гамбия', 'Грузия', 'Германия', 'Гана', 'Гибралтар', 'Греция', 'Гренландия', 'Гренада', 'Гваделупа', 'Гуам', 'Гватемала', 'Гвинея', 'Гвинея-Бисау', 'Гайна', 'Гаити', 'Гондурас', 'Гон-Конг', 'Венгрия', 'Исландия', 'Индия', 'Индонезия', 'Иран', 'Ирак', 'Ирландия', 'Израиль', 'Италия', 'Ямайка', 'Япония', 'Иордания', 'Казахстан', 'Кения', 'Корея, Южная', 'Корея, Северная', 'Кувейт', 'Киргизстан', 'Лаос', 'Латвия', 'Лесото', 'Либерия', 'Лихтенштейн', 'Литва', 'Люксембург', 'Макао', 'Македония', 'Мадагаскар', 'Малави', 'Малайзия', 'Мальдивы', 'Мали', 'Мальта', 'Мавритания', 'Мексика', 'Микронезия', 'Молдова', 'Монако', 'Монголия', 'Монтсеррат', 'Марокко', 'Мозамбик', 'Мьянма', 'Намибия', 'Непал', 'Нидерланды', 'Новая Каледония', 'Новая Зеландия', 'Никарагуа', 'Нигер', 'Нигерия', 'Норвегия', 'Оман', 'Пакистан', 'Панама', 'Папуа Новой Гвинеи', 'Парагвай', 'Перу', 'Филлипины', 'Польша', 'Португалия', 'Пуэрто-Рико', 'остров Реюньон (Франция)', 'Румыния', 'Российская Федерация', 'Руанда', 'остров Святой Елены', 'Самоа', 'Сан-Марино', 'Саудовская Аравия', 'Сенегал', 'Сьерра-Леоне', 'Сингапур', 'Словакия', 'Словения', 'Соломоновы острова', 'Сомали', 'Южная Африка', 'Испания', 'Шри Ланка', 'Судан', 'Свазиленд', 'Швеция', 'Швейцария', 'Сирия', 'Тайвань', 'Таджикистан', 'Танзания', 'Таиланд', 'Того', 'Токелау', 'Тонга', 'Тринидад и Тобаго', 'Тунис', 'Турция', 'Туркменистан', 'Тувалу', 'Уганда', 'Украина', 'ОАЭ', 'Англия', 'Великобритания', 'США', 'Соединенные Штаты Америки', 'Уругвай', 'Узбекистан', 'Ванауту', 'Венесуэла', 'Вьетнам', 'Йемен', 'Замбия', 'Зимбабве'];
new Autocompleter.Local('demo-local4', tokens, {
'minLength': 1,
'selectMode': 'pick',
'overflow': true,
'injectChoice': function(token){
var choice = new Element('li');
new Element('img', {
'src': 'images/' + translit(token) + '.gif'
}).inject(choice);
new Element('img', {
'src': 'images/' + 'spacer.png'
}).inject(choice);
new Element('span', {'html': this.markQueryValue(token)}).inject(choice);
choice.inputValue = token;
this.addChoiceEvents(choice).inject(this.choices);
}
});
});