Introduction
Selecting elements from a browser combobox with a lot of elements is a fairly common, yet annoying task, primarily because of the lack of select-as-you-type behavior. Atleast in Internet Explorer, each keypress selects the first element in the combobox starting with the key pressed, so typing in the first two letters of the element to select will not work as expected. This article provides a short piece of JavaScript code that you can use to provide the select-as-you-type behavior, with very few modifications.
How It Works
The basic idea is to capture and append keypresses on a combobox and then look for elements in the combobox starting with the list of keys pressed by the user. Here is the code in its entirety:
var keysPressed = [];
function selectAsYouType(e)
{
var keyChar; var keyNum;
var comboBox;
if (window.event) {
keyNum = e.keyCode;
}
else
{
return true; }
keyChar = String.fromCharCode(keyNum);
comboBox = e.srcElement;
if (!comboBox)
{
return true; }
if (keyNum == 27) {
clearKeysPressed(comboBox);
}
else
{
return selectElement(comboBox, keyChar);
}
return true;
}
function clearKeysPressed(e)
{
if (e.srcElement)
keysPressed[e.srcElement]="";
}
function selectElement(comboBox, keyChar)
{
var i = 0;
var keysPressedSoFar = keysPressed[comboBox] || "";
keysPressedSoFar += keyChar;
keysPressed[comboBox] = keysPressedSoFar;
var options = comboBox.options;
for (i = 0; i<options.length; ++i)
{
if (options[i].text.toUpperCase().indexOf
(keysPressedSoFar.toUpperCase(), 0) == 0)
{
comboBox.selectedIndex = i;
return false; }
}
keysPressed[comboBox] = String(keyChar);
return true;
}
keysPressed is a global array that stores the keysPressed for each combobox in the page. Each combobox that needs the select-as-you-type behavior would need to add two handlers:
onkeypress="return selectAsYouType(event)" - This captures keypresses on the combobox
onblur="clearKeysPressed(event)" - This clears off the keyboard cache (for that combobox) when focus moves out of the combobox
For example:
<select onkeypress="return selectA(event)" onblur="clearKeysPressed(event)">
<option>A</option>
<option>B</option>
<option>AB</option>
<option>ABC</option>
<option>C</option>
</select>
The code is fairly straightforward. The selectElement function takes the current key pressed, appends it to the keys pressed so far and checks if any element in the combobox starts with a string made up of keysPressedSoFar. If there is no match, it returns true to revert to the default behavior of the browser.
Points of Interest
A possible improvement would be to use a better algorithm to search for elements starting with a particular string. This code has been tested with comboboxes containing ~2800 elements (Click here for an example) without any performance problems.
History
- Initial post - 12:11 PM 2/24/2007