Introduction
If you spend any time surfing the web you will find <select> lists. In all cases I've encountered the default single character searches are used to help you "quickly" find the list item you want. As an example, to reach North Carolina in a list of states you would type "N" which takes you to Nebraska. "O" will take you to Ohio, so you will quickly learn to type "N" and down arrow 6 times to get "North Carolina".
I think we can do better.
An auto searching <select> list would allow us to type "No" and automatically get "North Carolina". Mississippi and Arkansas are other good examples. A few lines of client side JavaScript can solve this nuisance. I've included examples of both types of <select> lists for USA states below so give them a try.
Standard Non Searching Select List
AutoSearching Select List
How it works
Basically the javascript code driving the AutoSearching <select> above records each keystroke in a hidden input tag and uses ALL keystrokes to search for a matching Option in the list. A few questions may come to mind, such as "How to you clear previously captured keystrokes?". The onBlur()
and onFocus()
events clear previous keystrokes but what about starting a new search without moving focus from the <select> list?. In this case I used the Delete key. I decided not to use BackSpace key for this since many browsers use BackSpace to navigate Back.
How to use AutoSearch <select>
First, add selectKeyDown()
, selectKeyPress()
, and clr()
javascript functions to your page as found in the source code download, or simply View->Source for this page.
Next, add onBlur()
, onFocus()
, onKeyPress()
, and onKeyDown()
event handlers to your <select> tags
Last, add a hidden input tag named "keys" to store the previous keystrokes
A little debugging in case you are an occasional fumble finger typist like me and your <select> tags will never be the same.
The Code
function selectKeyDown()
{
if(window.event.keyCode == 46)
clr();
}
function selectKeyPress()
{
var sndr = window.event.srcElement;
var pre = this.document.all["keys"].value;
var key = window.event.keyCode;
var char = String.fromCharCode(key);
var re = new RegExp("^" + pre + char, "i");
for(var i=0; i<sndr.options.length; i++)
{
if(re.test(sndr.options[i].text))
{
sndr.options[i].selected=true;
document.all["keys"].value += char;
window.event.returnValue = false;
break;
}
}
}
function clr()
{
document.all["keys"].value = "";
}
Tested Browsers
- Internet Explorer 6.0.2800
- Mozilla 1.2.1
TODO
- Add Netscape Navigator handling.
- Test other and older browsers.
- Let me here your comments on this.
History
Release 03/02/2003