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

Features

  • Use local data or Ajax request (JSON or XHTML) as data source.
  • Look and feel like the OS, visitors can use it without problems.
  • Intuitive navigation with mouse and keyboard.
  • Customizable behaviour with a lot of options and events.
  • Minimal effects to avoid noise in the workflow.

How to use

With JSON + PHP5/PDO

window.addEvent('domready', function() {
 
    new Autocompleter.Request.JSON('fe-searchuser', '/query_user.php', {
        'postVar': 'search'
    });
 
});

Your XHTML markup, no additional elements needed:

<input type="text" name="search" id="fe-search"/>

And the example PHP for the database query:

<?php
// query_user.php
 
$search = $_POST['search'];
$result = array();
 
// Some simple validation
if (is_string($search) && strlen($search) > 2 && strlen($search) < 64)
{
    $dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
 
    // Building the query
    $stmt = $dbh->prepare("SELECT name FROM users WHERE name LIKE ?");
 
    // The % as wildcard
    if ($stmt->execute(array($search . '%') ) )
    {
        // Filling the results with usernames
        while (($row = $stmt->fetch() ) )
        {
            $result[] = $row['name'];
        }
    }
}
 
// Finally the JSON, including the correct content-type
header('Content-type: application/json');
 
echo json_encode($result); // see NOTE!
 
?>

NOTE:(If you are scared of the PHP 5 example) PHP 5 is not needed, this is just an example! There are classes and native solutions for all languages, more information is available here: JSON.org (List at the bottom of the page)

The response for a “Har” search would look like:

["Harald","Haribald","Harold","Harry","Haribald"]

Documentation

Aaron Newton wrote some documentation for CNET Clientside, describing the Options, Events and some public methods:

External Autocompleter Documentation

Requirements

MooTools JavaScript Framework

Download MooTools 1.2 Core with at least these modules:

  • Element.Dimensions
  • Fx.Tween
  • Request.HTML (for HTML requests)
  • Request.JSON (for JSON requests)
  • DomReady (facultative)
  • Selectors (facultative)

Download

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.

Share it: Stumble it!Digg This!del.icio.us (387 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
    krzyko
    said 2 years ago (2 Points)
    For me (Autocompleter 1.1.1 with MooTools 1.2) Opera 9.50 was bailing out with an error :

    message: RegExp.prototype.test was called with the wrong number of arguments
    stacktrace: ... Line 307 of linked script http://digitarald.de/project/autocompleter/1-1/source/Autocompleter.js
    return (tokens || this.tokens).filter(regex.test, regex);
    ... and so on...

    So I've changed line 307 from:
    - return (tokens || this.tokens).filter(regex.test, regex);
    to the content adapted from 1.0 version:
    + return (tokens || this.tokens).filter(function(token){return regex.test(tokens || this.tokens);});
    and all started to work. Thank you digitarald!
  • reply
    Avatar
    skarlcf 1 Point
    replied 2 years ago (1 Point)
    I've got the same error with Opera 9.50 (Windows and Linux). I've changed code but problem still is appearing. Could you help me?
  • reply
    Avatar
    krzyko
    replied 2 years ago (1 Point)
    At least I can try. Can you put your example somewhere on the web and post a link to it?
  • reply
    Avatar
    JR
    said 2 years ago (2 Points)
    hi there

    I want the working example of this auto completer please can you let me know via email once you have it up and running..i see that you said you will be loading it by next week.....dude_gallary@Hotmail.com

    i looked for the working example with all the relevant files but cant find it on your website to download
    pls help as i would like to implement this on my personal website
  • reply
    Avatar
    said 2 years ago (2 Points)
    There's a bug in the Autocompleter.Ajax.Json.queryResponse() method (around line 422).

    Autocompleter.Base.update() expects the tokens variable to be an array. However, the Json queryResponse method returns a response object. This causes the if statement in update() (around line 269) to break when it checks for length and later when it runs the .each block (around line 273).

    The solution is to remove the tokens.length section from the if statement (around line 269) and have the Json queryResponse method return a Hash of the response object.

    Line 269 should look like:
    if (!tokens) {
    Line 422 should look like:
    this.update($H(response));

    Ideally, there would be a .length method for Hash, but MooTools 1.2 (trunk) doesn't currently have one.

    Hope that helps.
  • reply
    Avatar
    digitarald Site Owner
    replied 2 years ago (1 Point)
    Thx for the report and your help. Good catch on that domready error :) . You can not add a length property to Hash, but a method to get the length. I'll tweak the token check.
  • reply
    Avatar
    said 1 year 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 1 year 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 1 year 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 1 year 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 1 year ago (1 Point)
    super work . thanks for sharing
  • reply
    Avatar
    baaalji
    said 1 year ago (1 Point)
    super work . thanks for sharing
  • reply
    Avatar
    maxbow
    said 1 year 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 1 year 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 1 year 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 1 year 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 1 year 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 1 year 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 1 year 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" onfocus="javascript:if(this.value=='') {lol.observer.onFired();}" type="text">
  • reply
    Avatar
    Mathias
    said 1 year 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});
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.

Developer Resources & Tools