Click here to Skip to main content
Licence CPOL
First Posted 12 Aug 2011
Views 6,333
Downloads 324
Bookmarked 11 times

AutoComplete Textbox

By | 22 Aug 2011 | Article
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

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
QuestionThanks Pinmembertranquocdung4317:20 5 Jan '12  
QuestionCode is not working for chrome and firefox browsers PinmemberMember 31033734:54 16 Nov '11  
GeneralMy vote of 2 PinmemberPraveen Meghwal21:59 22 Aug '11  
GeneralMy vote of 5 Pinmembermhamad zarif21:29 22 Aug '11  
GeneralMy vote of 3 Pinmembermbcrump12:10 13 Aug '11  
GeneralRe: My vote of 3 PinmemberSreedhar Taduri18:57 14 Aug '11  
GeneralMy vote of 2 PinmemberWarrick Procter2:43 13 Aug '11  
GeneralMy vote of 2 PinmemberPetr Pechovic2:09 13 Aug '11  
SuggestionHave you heard about SQL injection PinmemberGiDEoN19824:58 12 Aug '11  
GeneralRe: Have you heard about SQL injection PinmemberPascal Ganaye5:20 12 Aug '11  
GeneralRe: Have you heard about SQL injection PinmemberSreedhar Taduri18:55 14 Aug '11  

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.

Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120517.1 | Last Updated 22 Aug 2011
Article Copyright 2011 by Sreedhar Taduri
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid