TRY I-Expence
Auto Complete textbox in ASP.Net using JavaScript
Suggestion to the user inputs in the text box is very useful on Web. This is just like Google Suggestions.
Posted Date: 09 Oct 2007
 

Description

Suggestion to the user inputs in the text box is very useful on Web. This is just like Google Suggestions.

Step 1 : Create JavaScript variable in Page Load event for storing data for auto complete popup.


//Register the cities for autocomplete
if (!Page.ClientScript.IsStartupScriptRegistered("City_AutoComplete"))
{
//Get the Cities
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("var city_data=new Array('Pune','aurangabad');");

Page.ClientScript.RegisterStartupScript(this.GetType(), "City_AutoComplete", sb.ToString(), true);

}


Step 2: Create a JScript file and place the below code. Refere this file into the ASPX page.

function showautocomplete(n,ac_array){
if (n.value == "") return 0;
if (event.keyCode == 8 && n.backspace){
n.value = n.value.substr(0,n.value.length-1);
n.backspace = false;
}

var r = n.createTextRange();
tmp= n.value;
if (tmp == "")return 0;
for (z=0;ztmp2 = ac_array[z];
count = 0;
for (i = 0;iif (tmp2.charAt(i).toLowerCase() == tmp.charAt(i).toLowerCase()){
count++
}
}
if (count == tmp.length){
diff = tmp2.length - tmp.length;
if (diff <= 0) break;
kap = "";
for (i=0;iif (i >= tmp.length) kap += tmp2.charAt(i);
}
n.backspace = true;
r.text += kap;
r.findText(kap,diff*-2);
r.select();
return 0;
}
}
n.backspace = false;
return 0;
}

Call this function on the textbox onkeyup event to show the auto complete like below.

... onkeyup=showautocomplete(this,nm) title=Opening name=fruit backspace="false">
... onkeyup="showautocomplete(this,fruits)" title=Opening name=Name backspace="false">

Run the ASPX Page in the browser.

 
Complete IT Solutions
Sign up for PayPal and start accepting credit card payments instantly.


Copyright © 2006-07 Pritam Baldota
Rights reserved. Please seek permission for reproduction.