Ajax AutoComplete Extender like Google

 

You might have noticed while searching in Google, the search keywords will be bold. Let’s see how to perform this in ASP.NET. We can do this using JavaScript

<script>

function BoldChildren(){

var behavior = $find('AutoCompleteEx');

var target = behavior.get_completionList();

if (behavior._currentPrefix != null)

{

var prefix = behavior._currentPrefix.toLowerCase();

var i;

for (i = 0; i <>

{

var sValue = target.childNodes[i].innerHTML.toLowerCase();

if (sValue.indexOf(prefix) != -1)

{

var fstr = target.childNodes[i].innerHTML.substring(0, sValue.indexOf(prefix));

var estr = target.childNodes[i].innerHTML.substring(fstr.length + prefix.length, target.childNodes[i].innerHTML.length);

target.childNodes[i].innerHTML = fstr + prefix + '' + estr +'';

}

}

}

}

function aceSelected(sourse, e)

{

var value = e.get_value();

if (!value)

{

if (e._item.parentElement && e._item.parentElement.tagName == "LI")

value = e._item.parentElement.attributes["_value"].value;

else if (e._item.parentElement && e._item.parentElement.parentElement.tagName == "LI")

value = e._item.parentElement.parentElement.attributes["_value"].value;

else if (e._item.parentNode && e._item.parentNode.tagName == "LI")

value = e._item.parentNode._value;

else if (e._item.parentNode && e._item.parentNode.parentNode.tagName == "LI")

value = e._item.parentNode.parentNode._value;

else

value = "";

}

sourse.get_element().value = value;

document.getElementById('<%=btnSearch.ClientID%>').click();

}

script>

The function BoldChildren() is the one which bolds the search content in the Autocomplete textbox and the function aceSelected() makes the search text normal and triggeres the search event

Your AutoComplete Textbox and the Search button Looks like this.

<asp:TextBox ID="txtSearch" runat="server" AutoCompleteType="Disabled"

CssClass="textbox1" Width="410px" ToolTip="Enter Search Term" >asp:TextBox>

<cc1:AutoCompleteExtender runat="server" ID="autoComplete1" CompletionListCssClass="AutoExtender" 

CompletionListItemCssClass="AutoExtenderList" CompletionListHighlightedItemCssClass="AutoExtenderHighlight"

BehaviorID="AutoCompleteEx" OnClientShown="ShowOptions" OnClientPopulated="BoldChildren" OnClientItemSelected="aceSelected"

CompletionInterval="1" CompletionSetCount="10" TargetControlID="txtSearch" ServicePath="http://www.Yoursite.com/Autocomplete.asmx"

ServiceMethod="GetCountriesList" MinimumPrefixLength="1" EnableCaching="true">cc1:AutoCompleteExtender>

With this we have implemented search similar to Google which bolds the user search keyword.

3 Comments

Comments have been disabled for this content.