MooTools’ AutoCompleter Plugin

By  on  
AutoCompleter

One of the famous MooTools plugins is Harald Kirschner's AutoCompleter plugin. AutoCompleter takes a term input by the user and searches for matches -- an obviously help to the user. Here's how to make the most of Harald's great plugin.

The XHTML

Single Search

<input type="text" name="search" id="search" /> <br /><br /><br /><br /> <h2>Multi-Search</h2> <textarea name="search2" id="search2" style="height:100px;"></textarea>

All we need to do is provide the textarea or input element -- AutoCompleter does the rest.

The CSS

#search,#search2			 { border:1px solid #ccc; padding:6px; width:400px; background:#fff; }
ul.autocompleter-choices 	 { position:absolute; width:339px; padding:0; list-style:none; z-index:50; background:#3b5998; border:1px solid #3b5998; top:0; }
ul.autocompleter-choices li { margin:0; list-style:none; padding:0px 10px; cursor:pointer; font-weight:normal; white-space:nowrap; color:#fff; font-size:11px; }
ul.autocompleter-choices li:hover { background:#eceff5; color:#3b5998; }
.search-working { background:url(/wp-content/themes/walshbook/images/indicator_blue_small.gif) 200px 7px no-repeat; }

We may style all of the elements however we'd like.

The MooTools JavaScript

window.addEvent('domready', function() {
	new Autocompleter.Request.JSON('search', 'get-terms.php', {
		'postVar': 'search',
		minLength: 3,
		maxChoices: 10,
		autoSubmit: false,
		cache: true,
		delay: 300,
		onRequest: function() {
			$('search').setStyles({
				'background-image':'url(indicator_blue_small.gif)',
				'background-position':'350px 7px',
				'background-repeat':'no-repeat'
			});
		},
		onComplete: function() {
			$('search').setStyle('background','');
		}
	});
	
	
	new Autocompleter.Request.JSON('search2', 'get-terms.php', {
		'postVar': 'search',
		minLength: 3,
		maxChoices: 10,
		autoSubmit: false,
		cache: true,
		multiple: true,
		delay: 300,
		onRequest: function() {
			$('search2').setStyles({
				'background-image':'url(indicator_blue_small.gif)',
				'background-position':'350px 7px',
				'background-repeat':'no-repeat'
			});
		},
		onComplete: function() {
			$('search2').setStyle('background','');
		}
	});
	
});

We've chosen to use the JSON version of AutoCompleter (we may also use "Local" and "Request"). Harald's provided so many options for AutoCompleter that I can't mention them all here. We've chosen to show the most prominent.

We've created two AutoCompleter.Request.JSON instances -- one that will allow only one value and one that will allow for multiple term lookups. To add a bit of style and communicate to the user that the AutoCompleter is looking for like terms, we add a background image upon request and then hide it when the request has been completed.

The PHP

//settings, vars
$min = 3;
$max = 50;
$choices = 10;
$search = (string) stripslashes(strip_tags($_POST['search']));
$result = array();

//quick validation
if(strlen($search) >= $min && strlen($search) >= $max)
{
	//connect to the database
	$link = mysql_connect('host','username','password') or die('cannot connect');
	mysql_select_db('dbname',$link) or die('cannot select db');
	
	//query the db to find matches
	$qresult = mysql_query("SELECT DISTINCT term FROM search_terms WHERE term LIKE '%".mysql_escape_string($search)."%' LIMIT $choices",$link);
	
	//create a result array based on db results
	while($row = mysql_fetch_assoc($qresult)) { $result[] = $row['term']; }
	//sleep(4); // delay if you want
	
	//push the JSON out
	header('Content-type: application/json');
	echo json_encode($result);
}

After some basic validation, we connect to the database, search for like terms, and return a JSON-encoded string for use by AutoCompleter.

It's that simple! Using some a little PHP, CSS, and MooTools JavaScript, your search boxes can go from boring and basic to fun and helpful!

Recent Features

  • By
    Designing for Simplicity

    Before we get started, it's worth me spending a brief moment introducing myself to you. My name is Mark (or @integralist if Twitter happens to be your communication tool of choice) and I currently work for BBC News in London England as a principal engineer/tech...

  • By
    I&#8217;m an Impostor

    This is the hardest thing I've ever had to write, much less admit to myself.  I've written resignation letters from jobs I've loved, I've ended relationships, I've failed at a host of tasks, and let myself down in my life.  All of those feelings were very...

Incredible Demos

Discussion

  1. The request is fast, but the output is some slowly (maybe for the big query), but nice script!

  2. @shakaran: I code the PHP script to have a delay. I’ve shortened the delay on the return script so it should be much faster now.

  3. (sorry I don’t see the sleep() xD) Much better!
    Maybe in the sql query, you can use MATCH AGAIN and not LIKE (I believe that MATCH AGAIN is more faster than LIKE or that I read).

  4. Rakesh Juyal

    comment the sleep!!! It is ultra slow Walsh, but looks cool ;)

    he who go to ‘sleep‘ with ichy bum wakes
    up with smelly finger

  5. @Rakesh Juyal: Delay removed.

  6. Simon Charette

    What about using a GET request?

  7. This is pretty cool…it’s still a bit slow though – isn’t there a way to load a predefined list of results based on often searched terms or something?

  8. Great tool! The number of searches can be added to the database, so the most number of searches and the search can be sorted according can be shown, likes Google…

  9. Facundo

    Hi David,

    I’ve been looking for an autocompleter plugin that performs well in Spanish, but I haven’t found one that fits my needs and I couldn’t solve it by myself. The problem is the accented letters,I want the results to be shown whether the user writes with or without an accent. Maybe you can help me with this.

    thanks!

  10. @Facundo: You can try with utf8_encode in php ;) It display correct letters as ñ or á

  11. Robert

    Hey,
    There may be a good idea to show how You can use autocompleter as replace for combo-box with different text and value.

    I use for this autocompleter HTML request and parse the result in injectChoice and onSelection functions (there is an id passed in a hidden span).
    Or maybe there is a better way to do this?

    also Your example does not show the current selection if You use arrows insted of mouse pointer.

    Thanks.

  12. Robert

    @Facundo
    You probably have to change regexp which is used in autocompleter…

  13. Guille

    Hi guys,
    I’m write from Argentina. I giving firts steps on Mootools Ajax, and i trying to experiment with diferents libraries. Probing the autocompleter plugin example in this page, I find with a little trouble: where I can download “Autocompleter.js” “Autocompleter.Request.js” and “Observer.js”?? Thank you very much!!

  14. Facundo

    Hola Guille,

    En la página oficial del plugin, http://digitarald.de/project/autocompleter/ .Suerte!

  15. Guille

    Gracias Facu! Ya las baje, las instale y esta todo funcionando!. Una sola diferencia entre el ejemplo online y la que yo instale en mi xampp (que modifique para que funcione como HTML en vez JSON): cuando recorro la lista de sugerencias con las flechas del teclado, mi seleccion no se “ilumina”, es decir, no se resalta la opcion de las lista sobre la que estoy en cada momento, a medida que me muevo entre las opciones solo cambia el contenido de la caja de texto principal. Supongo que es algo del CSS. Algun tip?

  16. Zoran

    Thank you for this beautiful example… I really like JQuery better than MooTools, but your examples make me not give up on MooTools.
    I implemented it on a project i am working on and it looks so nice, it even recognizes the Macedonian Cyrillic letters… So cool

  17. Hi guys,

    I am a little bit green on this… can make it work and nothing is coming up when i type anything… can anyone give a download-able example? Thanks a lot

  18. I have created an index.php file having the dialog box for the search, a file containing the Mootools script and another get-terms.php.

    I have downloaded the Mootools file and included in the index.php file…

    I run the index.php and when i run everything… nothing happens when i type in the dialog box :(

    I am still new to JSON, JQuery and Mootools… If anyone can help me, it would be really appreciated.

  19. Hi,
    Great post, but is there anyway to send more another value to a hidden field? I am thinking about using this to select a value (as it currently does), but also send another value from the same row on the database to a hidden field within the form? Is this at all possible?

  20. jpod

    nice one man… but i still confuse when i want to get some index on result suggest… example:
    {“field1”: “field1value”,”field2″:”field2value” }

    and then i want to get value field1 when i click my choice.. can you show me advance sample to do that david? great job man..!!

  21. I am using jQuery on my site, do you suggest finding a jQ “Auto Completer” or should I go with the MooTools plugin? I don’t want to use MooTools, because thats two frameworks… I rather stay dedicated to jQ.

  22. tom

    this script does not work in my case. is there missing anything ? Where can i get an explanation how to use this autocomplete package ?

  23. Is it possible to submit the auto completer “onClick”.

  24. Chris

    This looks great, and I’m trying to understand the code.

    I’m looking at the source code of your Demo page, and I can see all the elements you describe above in the source code, ie; the XHTML, CSS, Mootools javascript parts, but I can’t see the PHP you describe above, where you’re making the database connection etc. As far as I can tell the JSON is calling the same ‘autocompleter.php’ webpage, but I can’t the the mysql connection and SQL SELECT statements. Can you help me?

  25. Could you please show an example of usage of injectChoice?
    Like for instance when the results from the database query return 2 columns, and you must display col1 to the user and use col2 to automatically select another control.
    Simple example: search for a city and automatically fill in the province to which that city belongs.
    Thanks a lot…
    Otherwise, for users that are not geniouses in mootools, finding our way through these options is dare i say impossible :(

  26. Very useful Davis as always. Article saved me atleast a day.

    Cheers!

  27. Hi david, the demo is not case-sensitive. How did you do that? Does “filter” and “filterCase” has something to do with it?

  28. Scott Benton

    Hey. First of all thanks for the demo. I’ve got this loaded up in a Joomla template. MooTools-core and MooTools-more are both loaded. However, I’m getting the following in the FireBug console when I load the page:

    Autocompleter is not defined
    [Break On This Error]

    new Autocompleter.Request.JSON('search', 'mySearchScript.php', {     autocomplete.js     line 3
    

    The autocomplete.js is a copy-paste from above, with the script name changed to point to my PHP script. Has anyone else gotten this up and running in Joomla? Since Joomla has Mootools built in, I thought it would be a no-brainer :(

  29. The script does not work any more …
    We have a Javascript error :

    Erreur : TypeError: choice.addClass is not a function
    Fichier Source : http://davidwalsh.name/demo/Autocompleter.js
    Ligne : 298

    Somebody has an idea ?

  30. About the choice.addClass error, look for function addChoiceEvents in Autocompleter.js and take off the brackets around el as below

    addChoiceEvents: function(el) {
    	return el.addEvents({
    		'mouseover': this.choiceOver.bind(this, el),
    		'click': this.choiceSelect.bind(this, el)
    	});
    }
    
  31. Demo’s not working at first glance. Tried a few letters in the fields and zero suggestions or overlays showed up.

  32. Gaudy

    Is there any way to port this to usersrccipt for an existent text field?

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!