Zur Zeit wird gefiltert nach: Sebastian Koch
Filter zurücksetzen

05.02.2010
20:48

Activating Autocompleter in script.aculo.us when entering a field (on Focus)

Autocompletion is a very useful AJAX feature: it allows the user to enter common values in fields very fast. By default, autocomplete activates after you type in the first letter. If you only have a few values in the autocomplete list, this is not very useful. Better would be to show the autocomplete list as soon as the user enters the field (the field is becomes focus).

For example we may have a field named color and would like to propose only a few values to the user. Because autocomplete starts after typing the first letter, the user will never see all suggestions we provide for the field. It would be more useful to provide a list of colors instantly when the user enters the field. By default this does not work with script.aculo.us. The script.aculo.us autocompleter offers the option minChars. But this parameter can not be set to 0, because 0 is evaluated as Boolean false and triggers the default value which is 1.

Example:

new Ajax.Autocompleter('DocumentJournalTitle', 'DocumentJournalTitle_autoComplete',
'/autoComplete/journal_title',
{minChars:0, frequency:0.1});

This does not work as expected: Autocomplete is still triggered after typing the first character.

I developed a short work around:

Set minChars to -1, this evaluates to true and is smaller or equal to 0:

<input name="journal_title" type="text" id="DocumentJournalTitle"
autocomplete="off" value="" />
<script type="text/javascript">
new Ajax.Autocompleter('DocumentJournalTitle', 'DocumentJournalTitle_autoComplete',
'/autoComplete/journal_title',
{minChars:-1, frequency:0.1});
</script>

This still does not work as expected. Why? The autocompleter only listens for keypress events. When the user enteres the field, the autocompleter is not activated. So we need to fire the event manually. This works this way:

<input name="journal_title" type="text"
onFocus="doFireEvent(this,&#039;keydown&#039;);"
id="DocumentJournalTitle" autocomplete="off" value="" />
<script type="text/javascript">
function doFireEvent(elem,event){
// IE
if (document.createEventObject){
var e = document.createEventObject();
return elem.fireEvent('on'+event,e)
}
// firefox and others
else{
var evt = document.createEvent("HTMLEvents");
evt.initEvent(event, true, true ); // event type,bubbling,cancelable
return !elem.dispatchEvent(e);
}
}
new Ajax.Autocompleter('DocumentJournalTitle', 'DocumentJournalTitle_autoComplete',
'/Entwicklung/StudyBase/documents/autoComplete/journal_title',
{minChars:-1, frequency:0.1});
</script>

And now the autocomplete box will show as soon as the field gets focused :-)

Weiterer Text