Click here to Skip to main content
Click here to Skip to main content

Auto select (Incremental search, Auto-complete) an item from a dropdown as user keys in

, 23 Sep 2008
Rate this:
Please Sign up or sign in to vote.
HTML lacks the auto-select feature for dropdowns. Users familiar with desktop applications expect browsers to select the correct item from a dropdown list as they key in. I am trying to solve this using simple JavaScript.

Sample screenshot

Introduction

Normally, HTML does not support nearest match. It always treats each key stroke as the starting of a new search. But, that is useless. If I type 'C', it will go to the first item that starts with C; if I type 'O' immediately, it will go to the first item that starts with 'O'. But in this implementation, it will go to 'CO'.

If the user misspelled, the user can use the backspace key to delete the char 'O' and type another letter to select another item. The user can wait for 3 seconds to start a fresh search, or use backspace to delete the entire search key, or shift delete to restart again.

It finds the nearest possible match. So, it does not need to be in any order.

  1. Just include the .js file in the target HTML:
  2. <script language="JavaScript" src="dropdown.js"></script>
  3. Add these events to your dropdown field:
  4. onfocus="this.enteredText='';" onkeydown="return handleKey();" 
      onkeyup="event.cancelbubble=true;return false;" onkeypress="return selectItem();"

    For example:

    <select name="test" onfocus="this.enteredText='';" onkeydown="return handleKey();" 
      onkeyup="event.cancelbubble=true;return false;" onkeypress="return selectItem();">
    • onfocus resets the search text.
    • onkeydown handles certain keys (left, right, top, down, shift, delete, backspace) and takes the appropriate action.
    • onkeypress handles the selection of an item from the list.
    • onkeyup ignores the event as onkeypress has already handled the key stroke.
  5. Open the HTML file using IE.
  6. Type 'a', it will take you to the first item that starts with 'a'. Then, type 'b'; this will take you to the first item that starts with 'ab'. This uses a nearest match algorithm. So, the list does not need to be in any order.
    1. The user can search a string within a dropdown list.
    2. It automatically selects the list item that starts with the search key.
    3. The user can use backspace to delete a char before the current index from the search key.
    4. The user can use the delete button to delete a char after the current index from the search key.
    5. The user can use left or right arrow keys to move back and forth over the search key, and use delete or backspace to delete a char; the script will automatically find the item in the list, or enter a new char from the current index.
    6. Pressing the Shift and Delete keys will remove the search key and start over the search again.
    7. The user can see the search key on the Windows status bar. It shows the current index too.

I am adding Hugh Nelson's suggestion also here, so that it is available for every one. If you want to change all the dropdowns in a page to have this functionality, call the following in the onload event:

function setSelectEvents() {
    // set javascript event attributes
    // for all select items in the current page
    var selects = document.getElementsByTagName("select");
    var arrOnfocus = new Array(); // array of onfocus functions
    var arrOnkeydown = new Array(); // array of onkeydown functions
    var arrOnkeyup = new Array(); // array of onkeyup functions
    var arrOnkeypress = new Array(); // array of onkeypress functions

    for (var i = 0; i < selects.length; i++) {
        // we need to ensure that
        // we don't overwrite any existing function

        // save index to array as an element attribute
        // (using i directly did not work)
        selects[i].title = i;

        // onfocus
        if(typeof(selects[i].onfocus) == 'function') {
        // there is a pre-existing function
            // save pre-existing function
            arrOnfocus[selects[i].title] = selects[i].onfocus;
            selects[i].onfocus = 
              function() { arrOnfocus[this.title](); this.enteredText=''; }
              // set event to call our code plus the pre-existing function
        }
        else { // there is no pre-existing function
            selects[i].onfocus = function() { this.enteredText=''; }
        }

        // onkeydown
        if(typeof(selects[i].onkeydown) == 'function') {
        // there is a pre-existing function
            // save pre-existing function
            arrOnkeydown[selects[i].title] = selects[i].onkeydown;
            selects[i].onkeydown = 
              function() { arrOnkeydown[this.title](); return handleKey(); }
              // set event to call our code plus the pre-existing function
        }
        else { // there is no pre-existing function
            selects[i].onkeydown = function() { return handleKey(); }
        }

        // onkeyup
        if(typeof(selects[i].onkeyup) == 'function') {
        // there is a pre-existing function
            // save pre-existing function
            arrOnkeyup[selects[i].title] = selects[i].onkeyup;
            selects[i].onkeyup = 
              function() { arrOnkeyup[this.title](); 
                           event.cancelbubble=true;return false; }
              // set event to call our code plus the pre-existing function
        }
        else { // there is no pre-existing function
            selects[i].onkeyup = 
              function() { event.cancelbubble=true;return false; }
        }

        // onkeypress
        if(typeof(selects[i].onkeypress) == 'function') {
        // there is a pre-existing function
            // save pre-existing function
            arrOnkeypress[selects[i].title] = selects[i].onkeypress;
            selects[i].onkeypress = 
               function() { arrOnkeypress[this.title](); return selectItem(); }
               // set event to call our code plus the pre-existing function
        }
        else { // there is no pre-existing function
            selects[i]. &#246;nkeypress = function() { return selectItem(); }
        }
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

senthil karuppaiah
Web Developer
United States United States
Fourteen years of progressive experience in Software Product Development, tactical planning, project and client management, demonstrated success in leadership, critical thinking, problem solving and analysis. Diverse knowledge and experience with multiple development methodologies, reengineering, software engineering, and integration of heterogeneous systems.

Comments and Discussions

 
Newsmodified version PinmemberMember 35920213-Nov-08 4:09 
I modified the script:
1. to get rid of info in window.status - it creates dynamic div-s instead.
2. commented out timer function - user can press esc instead.
3. searches by partial string ('te' finds 'abtest')
 
HTML:
<html>
<head>
<!-- senthil karuppaiah -->
<!-- 12/22/2005 -->
<!--
Normally HTML does not support nearest match, It always treat each key stroke as starting of
new search. But that is useless. If I type 'C', it will go to first item starts with C,
if I type 'O' immediately, it will go to first item starts with 'O'. But in our case,
we go to 'CO'. If the user misspelled, he can use the backspace to delete the char 'O' and
return another letter. He can wait for 3 seconds to start fresh search or use backspace to
delete entire search key and restart again.
 
1) user can search the string within the dropdown list.
2) It automatically selects the list item that start with the search key
 
3) user can use backspace to delete a char before current index from the search key
 
4) user can use delete button to delete a char after current index from search key
 
5) user can use left or right arrow keys to move back and forth over the search key and use delete or backspace to delete a char, script automatically find the item in the list or enter a new char from the current index.
6) shift delete will remove the search key and start over the search again.
7) user can see the search key on top of dropdown.
 

-->
	<script type="text/javascript">history.go(1);</script>
	<script language="JavaScript" src="dropdown.js"></script>
</head>
<body bgcolor="#ffffff" marginheight="0" marginwidth="0" leftmargin="0" topmargin="0">
Type to search, press esc to cancel.
 

 

    <select name="test1" id="test1" onfocus="this.enteredText='';createDiv(this);" onblur="removeDiv(this);" onkeydown="return handleKey();" onkeyup="event.cancelbubble=true;return false;" onkeypress="return selectItem();">
     <option value="1">test</option>
     <option value="1">mtest</option>
     <option value="1">atest</option>
     <option value="1">abtest</option>
     <option value="1">abctest</option>
     <option value="1">abcdtest</option>
     <option value="1">abcdetest</option>
     <option value="1">abcdeftest</option>
     <option value="1">12/04/2005</option>
     <option value="1">01/04/2005</option>
	 <option value="1">acb'test</option>
	 <option value="1">$123.00</option>
	 <option value="1">-$123.00</option>
	 <option value="1">$123</option>
     <option value="1">acbtest</option>
     <option value="1">100,000</option>
     <option value="1">111,000</option>
     <option value="1">90,000</option>
     <option value="1">8,000</option>
     <option value="1">8,001</option>
      <option value="1">8,301</option>
     </select>
 

 
<select name="test2" id="test2" onfocus="this.enteredText='';createDiv(this);" onblur="removeDiv(this);" onkeydown="return handleKey();" onkeyup="event.cancelbubble=true;return false;" onkeypress="return selectItem();">
	 <option value="1">$123.00</option>
	 <option value="1">-$123.00</option>
	 <option value="1">$123</option>
     <option value="1">acbtest</option>
     <option value="1">100,000</option>
     <option value="1">111,000</option>
     <option value="1">90,000</option>
     <option value="1">8,000</option>
     <option value="1">8,001</option>
      <option value="1">8,301</option>
     </select>
</br></br></br></br></body>
</html>
 
Javascript (dropdown.js):
var _offsetTop=0;
var _offsetLeft=0;
var _offsetLeftClip=0;
 
function findPos(obj) {
  // Credit for this function: http://www.quirksmode.org/js/findpos.html
  // Visit the URL for a complete tutorial on this function
  var curleft = curtop = parent_offSetLeft = parent_offSetTop = 0;
  if (obj.offsetParent) {
     curleft = obj.offsetLeft
     curtop = obj.offsetTop
     curwidth = obj.offsetWidth;
     while (obj = obj.offsetParent) {
        curleft += obj.offsetLeft
        curtop += obj.offsetTop
        if(obj.id) {
           parent_offSetLeft = obj.offsetLeft;
           parent_offSetTop = obj.offsetTop;
         }
     }
  }
  return [curleft,curtop,curwidth,parent_offSetLeft,parent_offSetTop];
}
 

function createDiv(inpObj)
{ 
 

var _div = document.createElement('div');
var _text = document.createTextNode('');
_div.appendChild(_text);
 
_div.setAttribute("id", "div"+inpObj.id);
 

  
  // Positioning of the div

  _div.style.position = "absolute";
  ofs=findPos(inpObj);       
  
                          
  _div.style.top=(ofs[1]+_offsetTop+(ofs[4]*-1)-18)+'px';      
  _div.style.left=(ofs[0]+_offsetLeft+(ofs[3]*-1))+'px';    
                                                              
  _div.style.width=(inpObj.offsetWidth+_offsetLeftClip)+'px';
 
document.body.appendChild(_div);
}
 
function removeDiv(inpObj)
{ 
 
var _div = document.getElementById("div"+inpObj.id);
 
document.body.removeChild(_div);
}
 
function handleKey(e)
{
    keycode = event.keyCode;
    ele = event.srcElement;
    
    if(ele != null) {
				if(keycode == 8 || keycode == 127) // backspace
				{
					if(isNaN(ele.insertIndex) || ele.insertIndex == -1) {
						ele.enteredText = ele.enteredText.substring(0,ele.enteredText.length-1);
						ele.insertIndex = -1;
					}
					else{
						ele.enteredText = ele.enteredText.substr(0,ele.insertIndex-1) + ele.enteredText.substr(ele.insertIndex);
						if(ele.insertIndex > 0 ) {
							ele.insertIndex = ele.insertIndex - 1;
						}
					}
					resetTime(ele);
					event.cancelbubble=true;
					setSelected(ele);
					return false;
				}
				else if(keycode == 46){  // delete
					if(event.shiftKey) {
						ele.enteredText = "";
						ele.selectedIndex=0;
						ele.insertIndex = -1;
					}
					else {
						ele.enteredText = ele.enteredText.substr(0,ele.insertIndex) + ele.enteredText.substr(ele.insertIndex+1);
					}
					resetTime(ele);
					setSelected(ele);
				}
				else if(keycode == 37){ // left arrow
					 if(isNaN(ele.insertIndex) || ele.insertIndex == -1) {
						ele.insertIndex = ele.enteredText.length-1;
					 }
					 else {
						if(ele.insertIndex > 0 ) {
							ele.insertIndex = ele.insertIndex - 1;
						}
					 }
					 resetTime(ele);
					 setSelected(ele);
				}
				else if(keycode == 39){ // right arrow
					 if(isNaN(ele.insertIndex) || ele.insertIndex == -1) {
						ele.insertIndex = ele.enteredText.length;
					 }
					 else {
						if(ele.insertIndex < ele.enteredText.length) {
							ele.insertIndex = ele.insertIndex + 1;
						}
					 }
					 resetTime(ele);
					 setSelected(ele);
				}
				else if(keycode == 9 || keycode == 39 || keycode == 40 ){ // tab,up and down arrow
					event.cancelbubble=false;
					ele.enteredText = "";
					ele.insertIndex = -1;
					return true;
				}
 

	}
	return true;
}
function resetTime(ele){
		var curTime = new Date();
		var t = curTime.getTime() -  ele.lastEntered;
		ele.lastEntered = curTime;
 
var _div = document.getElementById("div"+ele.id);
oldNode = _div.firstChild;
        _div.removeChild(oldNode);
newNode = document.createTextNode( ele.enteredText);
        _div.appendChild(newNode);
 
}
function setSelected(){
	ele = event.srcElement;
	if (ele != null)
	{ // detect if element exists
		enteredText = ele.enteredText.toLowerCase();
		var selectIndex = -1;
		var selectLength = 20000;
		for(k=0; k < ele.children.length;k++){
		  txt = ele.children[k].text.toLowerCase()
		  if( txt.indexOf(enteredText) >= 0) {
			if(txt == enteredText){
		  	   selectIndex =k;
		  	   break;
		  	}
		  	var len = txt.length;
		  	if(selectLength > len) {
		  		selectLength = len;
		  		selectIndex = k;
		  	}
		  }
		}
		if(selectIndex > -1) {
		   ele.selectedIndex=selectIndex;
var _div = document.getElementById("div"+ele.id);
oldNode = _div.firstChild;
        _div.removeChild(oldNode);
newNode = document.createTextNode(ele.enteredText );
        _div.appendChild(newNode);
 
//		   window.status= ":Search Text=" + ele.enteredText +  ":Selected Index=" + ele.selectedIndex + ":Current position=" + ele.insertIndex;
		   return false;
		}
	} // end if
	return false;
}
function selectItem(txtField,tier2){
	ele = event.srcElement;
	if(isNaN(ele.insertIndex)) {
	  ele.insertIndex = -1;
	}
	if(ele.insertIndex > -1) {
		ele.enteredText = ele.enteredText.substr(0,ele.insertIndex) +  String.fromCharCode(event.keyCode) + ele.enteredText.substr(ele.insertIndex);
		ele.insertIndex = ele.insertIndex +1;
	}
	else {
		if(ele.enteredText == "") {
			ele.lastEntered = new Date();
		}
				else if(ele.enteredText==String.fromCharCode(27) ){ // esc
					ele.enteredText = "";
				}		
//else { //timer function is commented out
		  //var curTime = new Date();
		  //var t = curTime.getTime() -  ele.lastEntered;
		  //ele.lastEntered = curTime;
		  //if(t > 2000) {
	          //ele.enteredText = "";
 		  //}
//		}
if (event.keyCode!=27){
		ele.enteredText = ele.enteredText + String.fromCharCode(event.keyCode);}
else
{ele.enteredText ='';}
	}
	event.cancelBubble=true;
var _div = document.getElementById("div"+ele.id);
var oldNode = _div.firstChild;
 
        _div.removeChild(oldNode);
 
var newNode = document.createTextNode(ele.enteredText );
        _div.appendChild(newNode);
//	window.status= ":Search Text=" + ele.enteredText +  ":Selected Index=" + ele.selectedIndex + ":Current position=" + ele.insertIndex;
	return setSelected();
}

GeneralOrder of Selection. Pls respond. [modified] PinmemberNav1120-May-08 3:19 
GeneralRe: Order of Selection. Pls respond. PinmemberMember 35920213-Nov-08 21:28 
GeneralRe: Order of Selection. Pls respond. Pinmemberrajapandian8114-Dec-09 3:51 
GeneralCommercial usage PinmemberEmerson Takahashi20-Mar-08 6:20 
GeneralJavaScript PinmemberVinug29-Nov-07 18:47 
GeneralChange all select items in a page Pinmemberhugh.nelson5-Sep-07 18:48 
GeneralGreat simple solution Pinmemberhugh.nelson4-Sep-07 13:58 
QuestionWhat are these? (Ele.lastEntered, ele.EnteredText ) Pinmemberckwizard7719-Jul-07 5:50 
AnswerRe: What are these? (Ele.lastEntered, ele.EnteredText ) Pinmembersenthil karuppaiah6-Aug-07 6:18 
Generalproblem on old machines Pinmemberzum12327-Jun-07 3:04 
GeneralRe: problem on old machines Pinmembersenthil karuppaiah3-Jul-07 6:41 
GeneralRe: problem on old machines Pinmembertkrafael_net24-Sep-08 6:25 
GeneralProblems with status in IE 7 Pinmembermrortner10-Apr-07 6:38 
GeneralRe: Problems with status in IE 7 Pinmembermrortner10-Apr-07 6:41 
GeneralBrowser Limitations PinmemberTBBASEFLUG20-Nov-06 5:22 
Generalproblem with too many options PinmemberPranav Kaushik18-Aug-06 2:53 
GeneralRe: problem with too many options [modified] Pinmembersenthil karuppaiah18-Aug-06 19:03 
GeneralRe: problem with too many options PinmemberPranav Kaushik18-Aug-06 22:22 
GeneralRe: problem with too many options [modified] Pinmembersenthil karuppaiah19-Aug-06 4:34 
GeneralTerm Pinmembernorm .net6-Aug-06 21:34 
GeneralRe: Term Pinmembersenthil karuppaiah7-Aug-06 6:48 
AnswerIncremental Search Pinmemberrlivelyppk8-Aug-06 12:26 
GeneralRe: Incremental Search Pinmembernorm .net8-Aug-06 20:42 
GeneralRe: Incremental Search Pinmembersenthil karuppaiah9-Aug-06 5:59 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140721.1 | Last Updated 23 Sep 2008
Article Copyright 2006 by senthil karuppaiah
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid