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

AutoComplete Textbox

, 22 Aug 2011
Rate this:
Please Sign up or sign in to vote.
AutoComplete TextBox with simple JavaScript using XMLHTTP Request
textbox.JPG

Introduction

This is a simple Autocomplete Text box post which may help you. In this code, we are using XMLHTTP request object in JavaScript method to get the server data from ASP.NET page.

Using the Code

To achieve this first create two aspx pages one (Default.aspx) is for Autocomplete Text box, another (GetData.aspx) is to get the data from server. No need to write any server side code on Default.aspx.cs page. Just write some JavaScript methods for XMLHTTP request object and key press mouse over events and style for look and feel. See the below code:

//
   <html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Autocomplete Page</title>
    <style type="text/css">
    .row{
	font-family:Verdana, Geneva, sans-serif;
	font-size:11px;
	color:#333;
	background-color:#FFF;
	text-align:left;
}
.highlight{
	font-family:Verdana, Geneva, sans-serif;
	font-size:11px;
	color:#333;
	background-color:#06C;
	text-align:left;
	color:#FFF;
}
    </style>
    <script type="text/javascript">

    function showHint(str)
{
var xmlhttp;
if (str.length==0)
  {
  document.getElementById("txtHint").innerHTML="";
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }

xmlhttp.open("GET","GetData.aspx?username="+str,true);
xmlhttp.send();
}

// key press events

current_row = 1;
var firsttime;
	nn=(document.layers)?true:false;
	ie=(document.all)?true:false;
	function keyDown(e) {

		var evt=(e)?e:(window.event)?window.event:null;
		if(evt){
			var key=(evt.charCode)?evt.charCode: 
			((evt.keyCode)?evt.keyCode:((evt.which)?evt.which:0));
			if (key == 38) {

			    id1 = document.getElementById('xx' + current_row);
			    if (id1) {
			        id2 = document.getElementById('xx' + 
				parseInt(current_row - 1));
			        if (id2) {
			            current_row = current_row - 1;
			            id1.className = 'row';
			            id2.className = 'highlight';
			            document.getElementById('txtname').blur();

			        }
			    }
			}
			else if (key == 40) {
			    id1 = document.getElementById('xx' + current_row);

			    if (id1) {

			            if (current_row == 1 && firsttime == undefined) {
			                id1.className = 'highlight';
			                document.getElementById('txtname').blur();
			                current_row = current_row - 1;
			                firsttime = 1;
			            }
			            else {
			                id2 = document.getElementById('xx' + 
						parseInt(current_row + 1));
			                if (id2) {
			                document.getElementById('xx1').className='row';
			                id1.className = 'row';
			                id2.className = 'highlight';
			                document.getElementById('txtname').blur();
			            }

			        }
			        current_row = current_row + 1;
			    }
			}

			else if (key == 13 || key == 9) {
			    id1 = document.getElementById('xx' + current_row);
			    if (id1) {

			        test(id1.innerHTML);

			    }
			}
			else if (key == 8) {
			current_row = 1;
			firsttime = undefined;
			}
		}
	}
document.onkeydown=keyDown;
if(nn) document.captureEvents(Event.KEYDOWN);
//place the selected value into text box and hide the result set table
function test(rname) {

    document.getElementById('txtname').value = rname;
    var tbl = document.getElementById('tblAuto');
    tbl.style.display = 'none';
}
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <table>
            <tr>
                <td >
                    <asp:TextBox ID="txtname"  runat="server"
                    onkeyup="showHint(this.value);" TabIndex="1" ></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    <span id="txtHint"></span>
                </td>
            </tr>
        </table>
    </form>
</body>
</html>

...

And GetData.aspx page should have only the below tag, delete all other content.

<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="GetData.aspx.cs" Inherits="GetData" %>

The below code needs to be written in the GetData.aspx.cs page:

using System;
using System.Data;
using System.Data.SqlClient;
using System.Text;

public partial class GetData : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection
    ("Data Source=.;Initial Catalog=pubs;User ID=sa;password=sa;");
    protected void Page_Load(object sender, EventArgs e)
    {
        StringBuilder sb = new StringBuilder();
        String strUserLike = Request.QueryString["username"];
        DataSet DS = new DataSet();

        int m;
        SqlDataAdapter ad = new SqlDataAdapter("select lname from employee
        WHERE  lname LIKE '" + strUserLike + "%' AND lname is not null ", con);
        ad.Fill(DS);
        m = DS.Tables[0].Rows.Count;
        sb.Append("<table id='tblAuto' bgcolor='#CCCCCC'>");
        for (int i = 1; i <= m; i++)
        {
            sb.Append("<tr  bgcolor=\"#FFFFFF\" ><td id=\"xx" + i +
            "\"  tabindex=\"2\" class=\"row\" onclick=\"test('" +
            DS.Tables[0].Rows[i-1][0] + "')\"  onmouseover=\"this.className=
            'highlight'\"  onmouseout=\"this.className='row'\">");
            sb.Append(DS.Tables[0].Rows[i-1][0]);
            sb.Append("</td></tr>");
        }
        sb.Append("</table>");

        Response.Write(sb.ToString());

Thanks! If you have any questions or any issues about the code, please drop in a comment below.

License

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

About the Author

Sreedhar Taduri
Software Developer (Senior) Agility E Services
India India
No Biography provided

Comments and Discussions

 
QuestionThanks Pinmembertranquocdung435-Jan-12 17:20 
QuestionCode is not working for chrome and firefox browsers PinmemberMember 310337316-Nov-11 4:54 
GeneralMy vote of 2 PinmemberPraveen Meghwal22-Aug-11 21:59 
GeneralMy vote of 5 Pinmembermhamad zarif22-Aug-11 21:29 
GeneralMy vote of 3 Pinmembermbcrump13-Aug-11 12:10 
GeneralRe: My vote of 3 PinmemberSreedhar Taduri14-Aug-11 18:57 
GeneralMy vote of 2 PinmemberWarrick Procter13-Aug-11 2:43 
GeneralMy vote of 2 PinmemberPetr Pechovic13-Aug-11 2:09 
SuggestionHave you heard about SQL injection PinmemberGiDEoN198212-Aug-11 4:58 
GeneralRe: Have you heard about SQL injection PinmemberPascal Ganaye12-Aug-11 5:20 
GeneralRe: Have you heard about SQL injection PinmemberSreedhar Taduri14-Aug-11 18:55 

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
Web04 | 2.8.140718.1 | Last Updated 22 Aug 2011
Article Copyright 2011 by Sreedhar Taduri
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid