Click here to Skip to main content
Licence CPOL
First Posted 9 Aug 2009
Views 38,309
Downloads 2,346
Bookmarked 18 times

Google Like Search TextBox

By | 11 Aug 2009 | Article
Google Like Search TextBox

Introduction

Many of us are using Google as a search engine. There are many reasons why we prefer Google, but one of the reasons is that Google suggests the possible search results and makes life easy. This search Suggest Textbox is very useful in many of our web applications. This article will help you to implement Search Suggest Textbox.

The user will type a character in the search textbox.Onkeyup event will get fired. It calls the method which is responsible for processing AJAX and receives a response. This response will be shown using DIV tags.

Background

AJAX Request will be processed through JavaScript using the XMLHttpRequest object.

With the XMLHttpRequest object, Internet Explorer clients can retrieve and submit XML data directly to a Web server without reloading the page. To convert XML data into renderable HTML content, use the client-side XML DOM or Extensible Stylesheet Language Transformations (XSLT) to compose HTML elements for presentation.

Using the Code

The code uploaded with this article contains mainly three files:

  1. Welcome.aspx
  2. SearchSuggest.js
  3. Result.aspx

Let's see each page in detail.

Welcome.aspx

This page has a search Textbox which displays the suggested search results while the user is typing in the search textbox.

<script language="JavaScript" type="text/javascript" src="SearchSuggest.js"></script>

The above code will import SearchSuggest.js file which is responsible for asynchronous postback.

 <style type="text/css" media="screen">	
          body 
          {
           font: 11px arial;
           }
	   .suggest_link 
	   {
	   background-color: #FFFFFF;
	   padding: 2px 6px 2px 6px;
	   }	
	   .suggest_link_over
	   {
	   background-color: #3366CC;
	   padding: 2px 6px 2px 6px;	
	   }	
	   #search_suggest 
	   {
	   position: absolute;
	   background-color: #FFFFFF;
	   text-align: left;
	   border: 1px solid #000000;			
	   }
	</style>

The above CSS code is for displaying selected/unselected from the suggestion results:

  <input type="text" id="txtSearch" name="txtSearch" alt="Search Criteria"     
	önkeyup="searchSuggest(event);" autocomplete="off" style="width: 544px" /> 
    
<div id=""search_suggest""></div>

    <input type="submit" id="cmdSearch" name="cmdSearch" 
			value="Search" alt="Run Search" />

txtSearch is the textbox for search. A method searchSuggest(event) from SearchSuggest.js is called on onkeyup event of it. We have to use onkeyup event so that on every single type of character, search suggest should process and give the corresponding result.
div search_suggest is hidden. It will be visible when a result is found for the corresponding typed characters.

Search submit button to search the results. The scope of this article is only upto the search suggest. One can enhance functionality on click of search button. This article does not have any code of onclick of Search button.

SearchSuggest.js

This file has code for AJAX Request using XMLHTTPRequest object.

function getXmlHttpRequestObject() 
{	
    if (window.XMLHttpRequest) 
    {
        return new XMLHttpRequest();	
        //For all the new browsers
    } 
    else if(window.ActiveXObject) 
    {
        //for IE5,IE6
        return new ActiveXObject("Microsoft.XMLHTTP");	
    }
    else
    {
        alert("Time to upgrade your browser?");	
      }
}

getXmlHttpRequestObject function will return the object of XMLHttpRequest depending upon the browser type. For Internet Explorer 5, Internet Explorer 6, it creates ActiveXObject from "Microsoft.XMLHTTP".

//Our XmlHttpRequest object to get the auto suggestvar 
searchReq = getXmlHttpRequestObject();

function searchSuggest(e) 
{
var key = window.event ? e.keyCode : e.which;

if (key==40 || key==38)
{
scrolldiv(key); 
}
else
{
if (searchReq.readyState == 4 || searchReq.readyState == 0) 
{
var str = escape(document.getElementById('txtSearch').value);
strOriginal=str;
searchReq.open("GET", 'Result.aspx?search=' + str, true);		
searchReq.onreadystatechange = handleSearchSuggest;
searchReq.send(null);	
}
} 	
}

The function searchSuggest will accept send request to Result.aspx and get response from it. While requesting, it will send the typed characters in Search Text box as querystring. Based on the search criteria result.aspx will process and send the result back. The result.aspx will send the response back in string format. The search result is concatenated by "~" , which will be handled in handleSearchSuggest method. and creates Div tag for each result.

Result.aspx.cs

The purpose of Result.aspx is to process Ajax request, so it does not have any code in HTML. It has only one line aspx page.
In the Code behind file, it validates the query string, takes search string and processes it to the database. Then response back result in string format. The generated string concatenated by "~".

private void Getresult()
    {
        DataTable dt = new DataTable();
       
         SqlConnection con = new SqlConnection
	("Data Source=Local;Initial Catalog=Rahul;User ID=sa;Password=sa");
         
        SqlCommand cmd=new SqlCommand();
        cmd.Connection=con;
        cmd.CommandType= CommandType.StoredProcedure;
        
        cmd.CommandText="SFund";

        //SFund is Stored Procedure Name which accepts 
        //parameter as @Client_Name and gives the search Result
        
        SqlParameter parClientName = new SqlParameter("@Client_Name", SqlDbType.VarChar);
        parClientName.Value = clientName;
        cmd.Parameters.Add(parClientName);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(dt);
        StringBuilder sb = new StringBuilder(); 
       
        if (dt.Rows.Count > 0)
        {
            for (int i = 0; i < dt.Rows.Count; i++)
            { 
                sb.Append(dt.Rows[i].ItemArray[0].ToString()  + "~");   
            }
        }

           Response.Write(sb.ToString());   

    }

Request

This is the first article I am posting on The Code Project. You can download the code from the link at the top of this article. 

License

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

About the Author

Rahul Garad

Software Developer (Senior)
Synechron Technologies,Pune
India India

Member

Working as a Lead-Software with 7.5 + years of Experience in Software development.

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
GeneralMy vote of 5 Pinmemberransems6:45 21 Jan '12  
GeneralRe: My vote of 5 PinmemberRahul Garad3:08 26 Mar '12  
QuestionWorked great with little or no code change Pinmemberransems6:43 21 Jan '12  
AnswerRe: Worked great with little or no code change PinmemberRahul Garad3:07 26 Mar '12  
AnswerWorks Fine PinmemberLakshmikantham Babu17:55 28 Nov '11  
GeneralRe: Works Fine PinmemberRahul Garad0:00 1 Dec '11  
QuestionSorry but am trying get this code to work. PinmemberBeverley14:55 27 Jul '11  
GeneralWhy you used two pages Pinmemberpraveen_gpk21:37 16 May '11  
GeneralNot working!! Pinmembermovies12323:03 18 Apr '11  
AnswerRe: Not working!! PinmemberRahul Garad1:42 3 May '11  
GeneralMy vote of 1 Pinmemberbabufff9:11 8 Jan '11  
GeneralMy vote of 2 Pinmember_Ainur0:21 10 Aug '09  
General[My vote of 2] It's simple PingroupMd. Marufuzzaman19:48 9 Aug '09  

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 12 Aug 2009
Article Copyright 2009 by Rahul Garad
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid