Home > Pure JavaScript Programming > Pure JavaScript Autocomplete in ASP Classic

Pure JavaScript Autocomplete in ASP Classic

In this post I implemented auto-suggestion using pure JavaScript. Although if you wanna use jQuery autocomplete you can use it. But if you are only using for this purpose then I would recommend not to use jQuery.

Firstly they are large files which will obviously affect your application’s performance. Secondly it is little slower in DOM traversing than pure JavaScript. Thirdly you can easily change JavaScript code, as you don’t necessarily need to have high level expertise in JavaScript.
In addition to that sometimes it has browser compatibility issues as well. So always try to use more standard and basic way in your programming. At least that’s my practice.

I implemented this JavaScript Autocomplete using ASP Classic as a server side language. But you can use any other language. I tried to make it as simple as possible but you can still make it more simple because there’s always a room for better.

This is the html:

 <input type="text" id="txtSearchEngines" class="data">
 <div id="suggestionBox" style="display:none">sss</div>

CSS classes:

#suggestionBox{
    position: absolute;
    z-index:999;
    border:01 gray solid;
    background-color:#E6E6E6;
    width: 300px;    
}
.suggest-data{
	line-height:20px;
    font-family: Tahoma;
    font-size:12px;
}
.rowSelected{
    background-color:#415C7C;
    color:white;
}

Here’s the JavaScript Code:

var request,xmlhttp,rowToSelect = 0,searchTextBox = document.getElementById("txtSearchEngines"),
_URL="AutoSuggest.asp";	
	BindSearchTextBox();
function BindSearchTextBox(){
	searchTextBox.addEventListener("keyup", KeyUpOnSearchTextBox,false);
	searchTextBox.addEventListener("keydown",HandleTabKey);
	document.getElementsByTagName("body")[0].addEventListener("click",CloseSuggestionBox);
}
function KeyUpOnSearchTextBox(e){
	var suggestBox = document.getElementById("suggestionBox");
	if((e.keyCode >= 65 && e.keyCode <= 90) || (e.keyCode == 40 || e.keyCode == 38 || e.keyCode == 8) ){				
		searchTextBox.removeEventListener("keyup",KeyUpOnSearchTextBox);
		if((e.keyCode == 40 || e.keyCode == 38 ) && suggestBox.style.display != "none"){    				
			SelectSuggestedRow(e.keyCode == 40 ? 1: -1 );
			BindSearchTextBox();
		}
		else{
			if(null != searchTextBox.value && "" != searchTextBox.value) SendAJAXRequestToServer(_URL+"?type=s&searchKey="+searchTextBox.value,ShowSuggestion,true);
			else{ HideSuggestionBox(); BindSearchTextBox();}
		}
	}
	else if(e.keyCode==13){searchTextBox.removeEventListener("keyup",KeyUpOnSearchTextBox); GetSelectedDetail(); }
}
function ShowSuggestion(){
	if (xmlhttp.readyState == 4) {
		if(xmlhttp.responseText != ""){
    		var suggestBox = document.getElementById("suggestionBox"),suggestRow=document.getElementById("suggest-rows");
    		suggestBox.style.display="";
    		suggestBox.style.top= searchTextBox.offsetTop + searchTextBox.offsetHeight+ 02;
    		suggestBox.style.left= searchTextBox.offsetLeft;
    		suggestBox.innerHTML = xmlhttp.responseText;    		
    		suggestBox.style.display="";	
    		SelectSuggestedRow(0);
		}
		else HideSuggestionBox();
		BindSearchTextBox();
	}
}
function CloseSuggestionBox(e){
	var eObj = e || window.event;
	if(eObj.target.className.indexOf("data") == -1) HideSuggestionBox();
}
function HandleTabKey(e){
	if(e.keyCode == 9) GetSelectedDetail();
	else if(e.keyCode == 27) HideSuggestionBox();
}
function HideSuggestionBox(){
	var suggestBox = document.getElementById("suggestionBox");
	suggestBox.innerHTML = null;
	suggestBox.style.display ="none";	
	rowToSelect=0;
	BindSearchTextBox();	
}
function HoverOverSuggestedList(obj){UnselectRow(); rowToSelect = obj.getAttribute("rowIndex"); SelectRow();}
function SelectRow(){document.getElementById("tblSuggest").rows[rowToSelect].className = "suggest-data rowSelected";}
function SelectedRowClicked(e){GetSelectedDetail();}
function UnselectRow(){	var suggestedTable=document.getElementById("tblSuggest");if(suggestedTable != null) suggestedTable.rows[rowToSelect].className = "suggest-data";}
function SelectSuggestedRow(rowCount){
	UnselectRow();
	if(rowToSelect == 0){ if(rowCount == 1) rowToSelect = rowCount;}
	else rowToSelect = rowToSelect + rowCount;
	if(rowToSelect >= document.getElementById("tblSuggest").rows.length){rowToSelect = rowToSelect - 1;SelectRow();}
	else SelectRow();
}
function GetSelectedDetail(){
	var suggestedTable=document.getElementById("tblSuggest");
	if(suggestedTable != null){
    	document.getElementById("lblName").innerHTML=suggestedTable.rows[rowToSelect].cells[1].innerHTML;
    	document.getElementById("lblValue").innerHTML=suggestedTable.rows[rowToSelect].cells[0].innerHTML;
	}
	HideSuggestionBox();
}
function SendAJAXRequestToServer(url,handler,ajax){
	xmlhttp= new XMLHttpRequest();
	xmlhttp.open('GET', url,ajax);
	xmlhttp.onreadystatechange = handler;
	xmlhttp.send(null);
}

ASP Classic code to return the suggestions for the search key;

'put your security/authenciation code here
response.write GetSuggestion
response.end
public Function GetSuggestion
	'Its just a demo you can write your code to get from database.
	dim searchKey 
		searchKey = Request.QueryString("searchKey")
	if(searchKey = "g") then
		GetSuggestion = "<table border='0' cellpadding='0' cellspacing='0' width='100%' id=""tblSuggest""><tr onclick=""SelectedRowClicked(event)"" onmouseover=""HoverOverSuggestedList(this)"" name='suggest-rows' rowIndex=""0"" class='suggest-data data' ><td class=""data"" style=""display:none"">1</td><td class=""data"" align='left' class=""data"">Google</td></tr><tr onmouseover=""HoverOverSuggestedList(this)"" onclick=""SelectedRowClicked(event)"" name='suggest-rows' class='suggest-data data' rowIndex=""2""><td class=""data"" style=""display:none"">3</td><td class=""data"" align='left'>Google2</td></tr></table>"
	else if(searchKey = "b") then
		GetSuggestion = "<table border='0' cellpadding='0' cellspacing='0' width='100%' id=""tblSuggest""><tr onclick=""SelectedRowClicked(event)"" onmouseover=""HoverOverSuggestedList(this)"" name='suggest-rows' class='suggest-data data' rowIndex=""1""><td class=""data"" style=""display:none"">2</td><td class=""data"" align='left'>Bing</td></tr></table>"
	end if
	end if
end function

Advertisements
  1. Uttam
    February 11, 2015 at 3:13 am

    Hi Muhammad, I liked the topic “Pure JavaScript Autocomplete in ASP Classic” it is exactly same as what I required. The problem is I am unable to make it work. Could you please send me the sample page so that I can implement as required. Thanks Uttam.

    • February 11, 2015 at 9:05 am

      @Uttam: Ok I created a sample ASP Classic(you can use any server side language like PHP, ASP.Net etc.) page to get and show the autocomplete using the sample code here in this article, so you can download. Click here to download.

      • Uttam
        February 12, 2015 at 8:59 am

        Thank you very much for the code. Now the issue I’m getting is “SCRIPT438: Object doesn’t support property or method ‘addEventListener'”. I hope my browser IE9 does not support. I’ll check. If you have any suggestions that would be helpful.

        • February 12, 2015 at 9:55 am

          As addEventListener doesn’t exist in IE 8 and earlier versions so to make it compatible just replace function BindSearchTextBox with this code;

          function BindSearchTextBox(){
              if(searchTextBox.addEventListener){
                  searchTextBox.addEventListener("keyup", KeyUpOnSearchTextBox,false);
                  searchTextBox.addEventListener("keydown",HandleTabKey);
                  document.getElementsByTagName("body")[0].addEventListener("click",CloseSuggestionBox);
              }else{
                  searchTextBox.attachEvent("onkeyup", KeyUpOnSearchTextBox);
                  searchTextBox.attachEvent("onkeydown",HandleTabKey);
                  document.getElementsByTagName("body")[0].attachEvent("onclick",CloseSuggestionBox);
              }
          }
          
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s