AutoCompleter (v1.1)
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.
Showcase “HTML Request”
The Action Happens Here
JavaScript & MooTools
document.addEvent('domready', function() { /** * Simple example, backend returns a list of <li> elements, * processed by Autocompleter.Request.HTML. */ var inputWord = $('demo-word'); new Autocompleter.Request.HTML(inputWord, 'script.php', { 'indicatorClass': 'autocompleter-loading' // class added to the input during request }); /** * Second input with extended list and custom inject * choice function. This one gets the first element * for the value and marks the searched string. */ var inputWord2 = $('demo-word2'); // Our instance for the element with id "demo-word2" new Autocompleter.Request.HTML(inputWord2, 'script.php', { 'indicatorClass': 'autocompleter-loading', 'postData': { 'extended': '1' // send additional POST data, check the PHP code }, 'injectChoice': function(choice) { // choice is one <li> element var text = choice.getFirst(); // the first element in this <li> is the <span> with the text var value = text.innerHTML; // inputValue saves value of the element for later selection choice.inputValue = value; // overrides the html with the marked query value (wrapped in a <span>) text.set('html', this.markQueryValue(value)); // add the mouse events to the <li> element this.addChoiceEvents(choice); } }); });
XHTML Markup
<form action="http://www.spanishdict.com/translate" method="get" id="form-demo"> <fieldset> <legend>Spanish Dictionary:</legend> <label> <span>Single word:</span> <input type="text" name="word" class="text" id="demo-word" /> </label> <label> <span>Single word (Extended list):</span> <input type="text" name="word2" class="text" id="demo-word2" /> </label> </fieldset> </form>
PHP Script
<?php // Processing a 6 MB dictionary file! ini_set('memory_limit', '128M'); $found = array(); $limit = 10; $value = $_POST['value']; if (is_string($value) ) { $words = file_get_contents('../es.csv'); preg_match_all('/^'. preg_quote($value) .'(.*)$/mi', $words, $match); $found = array_slice(array_values($match[0]), 0, $limit); } $extended = false; if (isset($_POST['extended']) && $_POST['extended']) { $extended = true; } foreach ($found as $word) { if ($extended) { echo "<li><span>$word</span><a class=\"demo-info\" href=\"http://www.spanishdict.com/translate?word=$word\">[ Ref ]</a></li>"; } else { echo "<li>$word</li>"; } } ?>
CSS Stylesheet
.demo-info { position: absolute; top: 0; right: 4px; padding: 1px 2px; font-size: 0.9em; color: #888; } input.autocompleter-loading { background-image: url(../spinner.gif); background-repeat: no-repeat; background-position: right 50%; }
This example and the accompanying sources/assets are © 2008-2009 by Harald Kirschner and available under The MIT License. For debugging and profiling the scripts and their markup download Firefox and use addons like Firebug and Web Developer Toolbar.
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);
}
});
});