Other versions:

AutoCompleter (v1.1)

Project AutoCompleter Showcase 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.

Showcases:

Showcase “JSON Request”

The Action Happens Here

Spanish Dictionary:

JavaScript & MooTools

document.addEvent('domready', function() {
 
	var inputWord = $('demo-word');
 
	// Our instance for the element with id "demo-word"
	new Autocompleter.Request.JSON(inputWord, 'script.php', {
		'indicatorClass': 'autocompleter-loading'
	});
 
 
	var inputWord2 = $('demo-words');
 
	// An element as indicator, shown during background request
	var indicator = inputWord2.getPrevious().getElement('.autocompleter-loading');
	indicator.setStyle('display', 'none');
 
	new Autocompleter.Request.JSON(inputWord2, 'script.php', {
		'indicator': indicator,
		'multiple': true,
		'selectFirst': true,
		'selectMode': false,
		'minLength': 2
	});
 
});

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>As Tags: <img src="../spinner.gif" class="autocompleter-loading" /></span>
			<textarea rows="100" cols="100" id="demo-words">playa, palma</textarea>
 
		</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);
}
 
header('Content-type: application/json');
echo json_encode($found);
 
?>

CSS Stylesheet

#demo-word
{
	width:				390px;
}
#demo-words
{
	height:				50px;
}
 
img.autocompleter-loading
{
	vertical-align:		top;
}
 

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.

Share it: Stumble it!Digg This!del.icio.us (375 Posts: )

discussion by DISQUS 261 Comments

Please use the support forums for discussing the project, asking questions or posting bug-fixes!

Sort:
Comments 1 – 20 of 261:
  • reply
    Avatar
    said 7 months ago (1 Point)
    im trying to include flag icons in my autocomplete results
    (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);
    }
    });
    });
  • reply
    Avatar
    Zoran
    said 8 months ago (1 Point)
    Thank you very much for this.... You just made my day.. Was struggling to get it to work, but it looks so nice and cool now... Thank you again :)
    Zoran from Macedonia
  • reply
    Avatar
    Jakso
    said 8 months ago (1 Point)
    Excellent work here!

    Wow, I am liking this functionality big time.

    Only issue, and others in this thread are requesting this feature, is how to integrate with a select list instead of a text input field?

    I'm going to rig my app to populate a select list on user selection of the typed ahead text, but would be much cleaner to have everything happen in one field (and set the select list value to the ID of the found search term and the display as the search term)
  • reply
    Avatar
    said 8 months ago (1 Point)
    Hi many thanx for your explanation...and i would like to ask if you could help me with something...How can i use this script for multiple input fields, each one of them will be using different tables of my database, like product name, brand etc...please help me guys...
  • reply
    Avatar
    baaalji
    said 8 months ago (1 Point)
    super work . thanks for sharing
  • reply
    Avatar
    baaalji
    said 8 months ago (1 Point)
    super work . thanks for sharing
  • reply
    Avatar
    maxbow
    said 8 months ago (1 Point)
    Hi,

    Very good work, thanks for sharing.

    I think your example is not totally correct. The 'url' param is not supposed to be in the options but the second argument of your constructor...
  • reply
    Avatar
    Sven
    replied 7 months ago (1 Point)
    Hi,

    have made the same experience today. The example still isn't fixed:-(
    Anyway: You've done a great job, thank you!
  • reply
    Avatar
    dissolute
    said 8 months ago (1 Point)
    addendum, the Clientcide version definitely fixes the IE Scrollbar issue, but it's not because they use IframeShim for OverlayFix (although it might be...)

    Now all I need to do is make Observer skip over list items that I've applied the choiceHead class to and I'm done!
  • reply
    Avatar
    dissolute 1 Point
    replied 8 months ago (1 Point)
    Ah, Clientcide skip the IE issue by changing the interaction - the choices only blur if you *click* outside them.
  • reply
    Avatar
    dissolute 1 Point
    said 8 months ago (1 Point)
    I'm building an Apple-style interface with this, with Featured results mixed with organic term suggestions. It works a treat except that it miscalculates the height of the block, as the feature results have and extra line of description. I can't work out where to fix it as the height seems to be based on the bottom of the container once built.

    My boss just asked me if I could make the "best bets" and "suggestions" sit side by side but when I did it with floated lists and a customChoices, the placement of the dropdown screwed up.

    BTW, I too have noticed the IE6/7 problem with the scrollbar (I turned overflow to false to "solve" it), I was considering extending the duration or playing with the Z-index to fix but haven't had much luck yet.

    I'll post my code when it's bedded down and working.
  • reply
    Avatar
    multeek
    said 9 months ago (1 Point)
    How I can display the autocomplete when the user is focused on the input element.
    Ex: if user focus the mouse over the input element, i want to display autocomlpte with all options listed. (for local autocomlpete)
    Are here any method for this?
    Thanks.
  • reply
    Avatar
    Szotyi
    replied 8 months ago (1 Point)
    it took for me 5 hours to figure that out :S
    lol = new Autocompleter.Local('category', maincategories, {
    'minLength': 0,
    'overflow': true,
    'filterSubset': true,
    'zindex': 50000
    });

    the important is set minLength to 0!

    and your textfield:
    <input id="category" name="category" type="text" onfocus="javascript:if(this.value=='') {lol.observer.onFired();}" />
  • reply
    Avatar
    Mathias
    said 10 months ago (1 Point)
    What was handy for me was adding a supply function for additional get parameters, so we could make easily make the choices depend on radio buttons etc.

    In query function of Autocompleter.Request we changed the end to

    var d = new Hash(data);
    if (this.options.supplyFunc != null) d.combine(this.options.supplyFunc());
    this.request.send({'data': d});
  • reply
    Avatar
    dude
    said 10 months ago (1 Point)
    looks like it's broken, probably your script link to mootools.
  • reply
    Avatar
    digitarald Site Owner
    replied 10 months ago (1 Point)
    Thanks for the hint, just fixed it.
  • reply
    Avatar
    digitarald Site Owner
    said 10 months ago (1 Point)
    Support and discussions moved to http://digitarald.de/forums/. If you already commented it here, please repost your question or bug report in the forum to get support.
  • reply
    Avatar
    Pepe Bondiola
    said 10 months ago (1 Point)
    It's awesome, thank you very much for developing the plugin.
  • reply
    Avatar
    Chris
    said 10 months ago (1 Point)
    I'm having issues with the horizontal scroll bar in Safari. When the resulting text is longer than the set width, the horizontal scroll bar appears. When using Firefox, I can scroll left/right using the mouse w/o any issues. However, when I use Safari the script doesn't realize that I'm still in the container and my choices are hidden (like I clicked somewhere else on the page) . Any ideas how to fix this so I can use the horizontal scroll bar when viewing results in Safari? I'm using the 1.1.1 version, will upgrading fix this?
  • reply
    Avatar
    elguapo09
    said 11 months ago (1 Point)
    Could you send it to me too?
Comments 1 – 20 of 261:

Post your comment

Please use the support forums for discussing the project, asking questions or posting bug-fixes!


Internet Consultant & Contractor

I'm available to combine forces with you and your team to find the most simple, elegant and convenient web solutions . I await your call.

If you just like my work and want to say Thank You, donate via PayPal or Amazon Wish List.

Feed Subscribe Feeds

Developer Resources & Tools

Web Design Agency on Mallorca d/vision