AutoComplete for Prototype.js

Ajax Powered Autocomplete for Prototype.js

autocomplete

I had to do an autocomplete textfield object on my actual job and looking for good resources on the net (never reinvent the wheel) I found the, very good job of Timothy Groves, Autosuggest. Nevertheless, I had a couple of issues to resolve as the object did not fully comply with the requirements of my job. It had to be part of a framework that makes and extensive use of Prototype.js 1.5.1. and also other features such as:
  • Icon Notifier (Spinner between Ajax calls)
  • Fire onAjaxFailure events when an error occurs during Ajax calls
  • Be able to set a custom width
  • A more flexible and dynamic creation of the autocomplete text field
Autosuggest was a great job, so I redefined the object and create AutoComplete. Once created, I thought that I should share with others my work as Timothy so kindly did and here it is. Hope this could help you out with your job and saves you hours of work.
TODO

The object is pretty complete but it could be nice to include more features. Here some of them:

  • Multiple column support. Just like gmail does, when a user enters a comma or semicolon, a new list is created when inserting any character after that. -done (thanks Réda HADJOUTI!)
  • Dynamic themes. Being able to change the style of the autocomple and dropdown list could be a really nice feature to have.
  • More effects to show/hide the dropdown list (SlideDown|SlideUp).
  • (If anyone of you does it, please contact me so whether I can post it on my blog or have a link to your project)

How it works

a) Configure the HEAD section of your HTML page:

<!-- insert the styles of the autocomplete box  -->
<link rel="stylesheet" href="css/autocomplete.css" type="text/css" media="screen" charset="utf-8" />

<!--  javascript libraries required  -->
<script type="text/javascript" src="js/prototype.js"></script>
<script type="text/javascript" src="js/autocomplete.js"></script>

b) Set the field’s onfocus event to automatically create the autocomplete box (you can also create them differently -ie onDOM load):

<!– IMPORTANT! MAKE SURE YOU INCLUDE autocomplete=’off’ on the field! -Thanks Ryan –>
<span class="ac_holder" style="margin-left:100px">
<input style="width: 200px" type="text" id="test_json" autocomplete=”off” onFocus="javascript:
var options = {
script:’test.php?json=true&limit=6&’, // test.php -> dropdown list results
varname:’input’, // post variable
json:true, // we expect the server response in JSON format
shownoresults:true, // displays no results message if no match is found
maxresults:16, // maximum number of results
callback: function (obj) { $(‘json_info’).update(‘you have selected: ‘+obj.id + ‘ ‘ + obj.value + ‘ (‘ + obj.info + ‘)’); }
};
// here is where we do the magic!
var json=new AutoComplete(‘test_json’,options);return true;" value="" />
</span><span id=’json_info’></span>

As you can see on the code, the ‘script’ property of the object is where we write the server page to call via AJAX in order to get the dropdown results. Let’s view the important lines within this test.php page:


// here we collect the POSTED variable
// what to search?
$input = strtolower( $_GET['input'] );
$len = strlen($input);
// how many results we display?
$limit = isset($_GET['limit']) ? (int) $_GET['limit'] : 0;

Now, the way you find matches from such POSTED variable is up to you, it could be checked against an array (as in the examples included) or against a database by using the LIKE SQL statement.

DOWNLOAD
Some people have problems downloading (I think it is a problem of the downloads manager plugin). If you have problems downloading please use this mirror.

http://www.ramirezcobos.com/wp-content/plugins/downloads-manager/img/icons/default.gif download: Ajax Powered AutoComplete (5.87KB)
added: 08/12/2009
clicks: 2767
description:



DISCLAIMER
I do not want to take any credit for the creation of the demos that I include within the compressed zip file. I have reused completely the work of Timothy, he should be the one granted with that.

  • #1 written by Duxcic
    about 7 months ago

    very gooood thanks

  • #2 written by Antonio Ramirez
    about 7 months ago

    You are welcome!

  • #3 written by Fabio
    about 7 months ago

    Thanks !

  • #4 written by IVAN
    about 7 months ago

    very well, i going to apply right now

  • #5 written by jollyr0ger
    about 7 months ago

    Hi, I can’t download the file. Can you check the if the archive is still there?

    Thanks

  • #6 written by Antonio Ramirez
    about 7 months ago

    Hey jollyr0ger!

    I have checked the link and it works ok. Have you been able to download it?


    jollyr0ger:

    Hi, I can’t download the file. Can you check the if the archive is still there?

    Thanks

  • #7 written by Vinny
    about 7 months ago

    Hi Antonio.
    I can’t download it too :(
    Can you check the link? It goes to the main page.

  • #8 written by Antonio Ramirez
    about 7 months ago

    I think it has something to do with the Downloads Manager WordPress plugin, but I have tried several times the link and it works!… Anyway, I will email you the file Vinny.

  • #9 written by Juan
    about 7 months ago

    Great job, thanks!

  • #10 written by Ryan
    about 6 months ago

    Awesome! I love it, Thanks. Just be sure to put

    autocomplete=”off”

    inside off the html input tag. I had a small problem with the browser’s autocomplete function opening on top of this one. I had this problem with Chrome if it is of any consequence.

  • #11 written by Antonio Ramirez
    about 6 months ago

    Thank you very Ryan… I will update the post with your suggestion. I completelly forgot to do it.

    Best

  • #12 written by IVAN
    about 6 months ago

    thanks men, i applied to a basic project but using mysql, if anyone need a example using mysql + php + this wonderfull autocomplete, let me know : )

  • #13 written by Antonio Ramirez
    about 6 months ago

    Thanks IVAN

  • #14 written by john
    about 6 months ago

    I can’t download the file.

  • #15 written by Antonio Ramirez
    about 6 months ago

    Hi John,

    I have updated the post and include a direct link for its downloading…

    Sorry all for this inconvenience.

  • #16 written by Charaf Anice
    about 6 months ago
  • #17 written by anup
    about 5 months ago

    thanks for this script. It is Very good one.

    I will surely use it future………

  • #18 written by Charlie
    about 5 months ago

    Hi, what format does the autocompleter expect the JSON response to be?

    E.g. {[result1, result2, result3]}

  • #19 written by Rafael Perelló
    about 2 months ago


    Charlie:

    Hi, what format does the autocompleter expect the JSON response to be?
    E.g. {[result1, result2, result3]}

    This is an example:
    {“results”:[{"id":0,"value":"SPAIN","info":"in Europe"},{"id":1,"value":"CHINA","info":"in Asia"}]}

  • #20 written by Rafael Perelló
    about 2 months ago

    I suggest a change in the code:

    var pos = this.fld.cumulativeOffset();

    to

    var pos = this.fld.viewportOffset();

    I did that change because the first failed when it’s inside a container that was scrolled. “cumulativeOffset()” didn’t change when the scroll is different to top position. Instead “viewportOffset()” reflects real position.

    Espero haberme explicado bien. Lo que quiero decir es que “cumulativeOffset” no tiene en cuenta el scroll del contenedor en el que estuviera, sin embargo “viewportOffset()” si tiene en cuenta ese movimiento y de esta forma queda anclado perfectamente.

    Buen trabajo Antonio
    Una cervecita para ti desde Mallorca.

  • #21 written by Antonio Ramirez
    about 2 months ago

    Gracias Rafael, la verdad es que tengo una nueva versión de la misma pero no he tenido tiempo todavia de subirla..: Estoy muy involucrado en nuevos proyectos y la verdad… El Blog lo tengo un poco dificil de actualizar!

  • #22 written by Jon B.
    about 1 month ago

    The zip file I downloaded only contained the file autocomplete.js, but the code and your comments make reference to other files (autocomplete.css, demos, etc.). I used the download link http://www.ramirezcobos.com/?file_id=2

    What am I missing?

  • #23 written by Antonio Ramirez
    about 1 month ago

    Please download the files of AutoComplete for JQuery and use the resource files but the JS files…

    Sorry for this inconvenience

  • #24 written by Henry Weber
    about 3 weeks ago

    Awesome job – this is absolutely great!

    One problem I’ve found though… do you know how I can get the results to show up in a jquery modal dialog?

    Thanks, Henry

  • #25 written by Jon B.
    about 3 weeks ago

    Thanks for that answer. I’m a big fan of the original bsn version, but since I already use Prototype, I was curious to see if your version was any better. I’ve gotten it to work, but there is one odd problem: The spinner never goes away. The “leftcap” image appears on focus, and as soon as the autocomplete is triggered the spinner appears, but then it never reverts back to the leftcap unless the entire page is reloaded. Any idea what might be causing this?

  • #26 written by Jon B.
    about 3 weeks ago

    Here’s an example of the problem I’m having with the spinner:

    http://www.track-blaster.com/wmbr/autocompletetest.html

  • #27 written by Jon B.
    about 2 weeks ago

    I do believe I’ve solved the problem. I looked in the jquery version and saw that Antonio had had a similar problem that he fixed by moving the notifier add code to a different part of the script. I found the equivalent section of the script in the Prototype version, moved the statements over, and voila! Problem is solved.

    For the record, I moved these statements,


    if( this.options.useNotifier )
    {
    this.fld.removeClassName('ac_field');
    this.fld.addClassName('ac_field_busy');
    };

    from lines 455-459 and inserted them right after line 243.