RobG wrote:
[...]
You'll have a cross-browser solution that uses less than half the code
that Goodman's solution does.
What the heck. Maybe not half the code, but the stuff below works better
and in Firefox too. Note that it is a bit jerky in IE, that is because
IE will do its own match first, then fire the keyup. So each time you
press a key, IE moves to that option, then calls the function which
likely changes the option based on the search string at that point.
I've added lots of comments to help out.
<script type="text/javascript">
// Global to remember keystrokes
var taObj = {
charsIn : '',
lastIdx : 0,
delay : 1000,
timer : null,
// Sets a timer that will clear the search string if no
// keys pressed before delay ends
setTimer : function(){
clearTimeout(this.timer);
this.timer = setTimeout('taObj.cleanUp()',this.delay);
},
cleanUp : function(){this.charsIn = '';}
}
function typeAhead(e, sel)
{
// Get a reference to the event so can check character entered
var e = e || window.event;
// Get the character entered
var let = String.fromCharCode(e.keyCode);
// If it's a word character or digit, add it to the search string
if (/[\w\d]/.test(let)){
taObj.charsIn += let; //(''==taObj.charsIn)? let : taObj.charsIn;
// Start/restart the timer
taObj.setTimer();
} else {
return;
}
// Get a reference to the list of options
var opts = sel.options;
// Build a regular expression to check with
var re = new RegExp('^' + taObj.charsIn,'i');
// Find a matching option
for (var i=0, len=opts.length; i<len; ++i){
// If find a match, make it selected & return
if (re.test(opts[i].text)){
sel.selectedIndex = i;
// Remember last selected
taObj.lastIdx = i;
return;
}
}
// If no match found, keep last match
sel.selectedIndex = taObj.lastIdx;
}
</script>
<form action="">
<div>
<select onkeyup="typeAhead(event, this);">
<option>Aardvarrk
<option>Adam
<option>Aden
<option>Adrian
<option>Ahmed
<option>Arthur
<option>Eve
<option>EveEve
<option>Evelyn
<option>Terry
<option>Thomas
<option>Trevor
</select>
</div>
</form>
--
Rob