The Autocompleter.Local in the Script.aculo.us Prototype-addon is quite nice. It can be used to get type-ahead into a field if you have a local JavaScript Array. I wanted to extend the functionality to have it behave as a Combobox, which is like a Select with a text input field. Here is how I did it, be advised it has some bugs, let me know if you have a better solution!
var Combobox={};
Combobox.Local=Class.create(Autocompleter.Local,{
initialize:function($super,element,update,array,options){
$super(element,update,array,options);
this.options.minChars=this.options.minChars||0;
Event.observe(this.element,'click',this.onClick.bindAsEventListener(this));
},
onClick:function($super,event){
if(Event.element(event).id){
if(this.active){
this.hasFocus=false;
this.active=false;
this.hide();
}else{
this.activate();
this.render();
}
return;
}
$super(event);
}
});
The CSS I use is a modified variant of the Autocompleter.Local wiki page:
.combo {
background-image:url(combo_select2.gif);
background-repeat:no-repeat;
background-position:right top;
margin-right:10px;
}
.combo:hover {
background-image:url(combo_select2.gif);
background-repeat:no-repeat;
background-position:right -18px;
}
div#autocomplete {
margin:0px;
padding:0px;
width:250px;
background:#fff;
border:1px solid #888;
position:absolute;
}
div#autocomplete ul {
margin:0px;
padding:0px;
list-style-type:none;
}
div#autocomplete ul li.selected {
background-color:#ffb;
}
div#autocomplete ul li {
margin:0;
padding:2px;
height:12px;
display:block;
list-style-type:none;
cursor:pointer;
}
Usage:
new Combobox.Local('textFieldID','outputDivID',array,options);
Example JavaScript:
var cities=new Array('Stockholm','Göteborg','Kiruna');
new Combobox.Local(
'cityField',
'autocomplete',
cities,
{
partialSearch:true,
fullSearch:true,
partialChars:0,
minChars:0
}
);
Example HTML:
The Windows XP style combobox image referenced in the CSS can be found here: