Autocomplete Without JQuery UI And Ajax ToolKit

As we know there is lots of auto complete provider apis, one of them is jquery auto complete plug-in and another is ajax auto complete control, we can implement auto complete functionally through these apis or ajax controls but there is some demerits of them below.

Demerits of jquery plug-in is very heavy plug-in make your page slower and increase of data size of page need to include auto complete css that also take some data size.

Demerits of ajax auto complete controls, Need script manager which render 4 or 5 .axd (JavaScript file) file taking more that 200 kb data size which is the cause of slower page speed and high page size.

So why you guys use ajax auto complete or jquery auto complete plug-in thing about you own function, I have found an alternate solution for that.

Make your own handler (.ashx) or you can make you web service (.asmx), fetch data from your database parse it as json datatype.

Call this aspx handler file (just like a service) from jquery .ajax method make html with this json and append it at your auto complete div container apply css as you need.

Hander (AutoC.ashx) part :


<%@ WebHandler Language="C#" Class="AutoC" %>

using System;
using System.Web;
using System.Text;
using System.Collections.Generic;
using System.Data;
using System.Web.Script.Serialization;

public class AutoC : IHttpHandler {

 public bool IsReusable{ get{ return false;} }
 public void ProcessRequest(HttpContext context)
 {
    JavaScriptSerializer jr = new JavaScriptSerializer();
    context.Response.ContentType = "application/json";
    string RawUrl = context.Request.RawUrl;
   
    string data = Encoding.UTF8.GetString(context.Request.BinaryRead(context.Request.TotalBytes));
    Dictionary<string, string> keyValue = jr.Deserialize<Dictionary<string, string>>(data);
    string prefixText = keyValue["prefixText"];
    short count=Convert.ToInt16(keyValue["count"]);
   
    context.Response.Write(jr.Serialize(GetCompletionList(prefixText, count)));
 }
 public static string[] GetCompletionList(String prefixText, short count)
 {
    List<string> items = new List<string>(count);
    DataTable dt = getData(prefixText, count);
    for (int i = 0; i < dt.Rows.Count; i++)
        items.Add(dt.Rows[i][0].ToString());
    return items.ToArray();
 }
 public static DataTable getData(string SearchData,short count)
 {
    DataTable dt = new DataTable();
    dt.Columns.Add(new DataColumn("result"));

    for (int i = 0; i < count; i++)
    {
        DataRow dr = dt.NewRow();
        dr[0] = i + ") " + SearchData;
        dt.Rows.Add(dr);
    }
    return dt;
 }
}

Call this AutoC.ashx from jquery part:

Here is the javascript code that is almost include all functionality just like auto Complete ajax control or auto complete jquery plugin just copy and paste any f where in the page and bind main function with text box as below.

Function upAutoComplete take 5 arguments "event of textbox, Object of textbox, auto complete div Container Client id , data count and Local Handler Service URL" Data Count is for filtering record count from server side handler.

Function downAutoComplete takes 3 arguments event of textbox, object of textbox, autoComplete container id.
 
<script type="text/javascript">
var $curLE = null;
function upAutoComplete(e, txtObj, ContainerId, Count, ServiceUrl) {
 var $this = $(txtObj);
 if ($this.val().length > 1) {
  var keyCode = [13, 37, 38, 39, 40];
  var $ACCont = $("#" + ContainerId);
  if (jQuery.inArray(e.keyCode, keyCode) == -1) {
    data = "{prefixText:'" + $this.val() + "',count:'" + Count + "'}";
    $.ajax({
    type: "POST",
    url: ServiceUrl,
    data: data,
    contentType: "application/json;",
    dataType: "json",
    success: function(response) {
        var divHtml = "";
        var id = 0;
        var onClk = "clickAutoCompleteLE(this,'" + $this.attr('id') + "','" + ContainerId + "')";
        $.each(response, function() {
            id = id + 1;
            divHtml += "<div id='divLE" + id + "' onclick=" + onClk + " class='completionListItem'>" + this + "</div>";
        });
        $ACCont.html(divHtml).css("display", "block");
        $curLE = null;
    },
    error: function(xhr, ajaxOptions, thrownError) {
        alert(xhr.status + ' ' + ajaxOptions + ' ' + thrownError);
    }
   });

   $this.blur(function() { hideAutoComplete(ContainerId); });
   $ACCont.mouseover(function() {
    $this.unbind('blur');

   }).mouseout(function() {
    $this.blur(function() {
        hideAutoComplete(ContainerId);
    });
   });
  }
 }
 else {
    hideAutoComplete(ContainerId);
 }
}
function clickAutoCompleteLE(divObj, txtId, ContainerId) {
  $("#" + txtId).val($(divObj).text());
  $("#" + ContainerId).html("").css("display", "none");
}
function hideAutoComplete(ContainerId) {
  $curLE = null; $("#" + ContainerId).html("").css("display", "none");
}

function downAutoComplete(e, txtObj, ContainerId) {
 var $this = $(txtObj);
 var FirstLE = $("#" + ContainerId + " :first");
 var LastLE = $("#" + ContainerId + " :last");
 var keyCode = [13, 38, 40];
 if (jQuery.inArray(e.keyCode, keyCode) != -1) {
  if ($curLE != null) {
      if (($curLE.attr("id") == FirstLE.attr("id")) && e.keyCode == 38) {
          removCssLE(); $curLE = null;
      }
      else if (($curLE.attr("id") == LastLE.attr("id")) && e.keyCode == 40) {
          removCssLE(); $curLE = null;
      }
  }
  if (e.keyCode == 40) {
      if ($curLE == null) {
          $curLE = FirstLE; addCssLE();
      }
      else {
          removCssLE(); $curLE = $curLE.next(); addCssLE();
      }
  }
  else if (e.keyCode == 38) {
      if ($curLE == null) {
          $curLE = LastLE; addCssLE();
      }
      else {
          removCssLE(); $curLE = $curLE.prev(); addCssLE();
      }
  }
  else if (e.keyCode == 13) {
      if ($curLE != null) e.preventDefault()
      $this.val($curLE.text()); $curLE.parent().html("").css("display", "none");
      $curLE = null;
  }
 }
}
function addCssLE() {
 $curLE.addClass("ListElementOnFocus");
}
function removCssLE() {
 $curLE.removeClass("ListElementOnFocus");
}
</script>
Or DownLoad Minify version of AutoComplete 2.0


Here is two main function need to bind with textbox KeyUp and KeyDown Event that is upAutoComplete Function and downAutoComplete Function.


<script type="text/javascript">
$(document).ready(function() {
    $("#txtAutoComplete").bind("keydown", function(e) { downAutoComplete(e, this, 'divContent') });
    $("#txtAutoComplete").bind("keyup", function(e) { upAutoComplete(e, this, 'divContent', '10','AutoC.ashx') });
});
</script>

Html part :

Here divContainer is the auto complete data container where data need to be append from jquery upAutoComplete Function.


<asp:TextBox ID="txtAutoComplete" runat="server" Width="365px" autocomplete="off" />
  
<div id="divContent" class="completionListElement" runat="server"
      style="display: none; max-height: 300px;">


Css part:

Css need to same name as given below "completionListItem" class applied with main Auto Complete divContainer, "completionListItem" applied with Each and every item of Aupto Complete divContainer, "ListElementOnFocus" applied with ListItem of Auto Complete divContainer item on keyBoard up and down selection. 

<style type="text/css">
 .completionListItem { border: 1px dotted #ACACAC; color: #006699; cursor: pointer; padding: 0 0 3px 3px; }
     
 .completionListItem:hover { background-color: #A5A5A5; color: White; cursor: pointer; }
     
 .completionListElement { background-color: White; border: 1px solid #ACACAC; font-family: Arial,sans-serif; font-size: 9pt; width: 376px; }
     
 .ListElementOnFocus { background-color: #A5A5A5; color: White; cursor: pointer; }
</style>

Download Autocomplete Without JQuery UI And Ajax ToolKit Full Code

DownLoad DotnetBull Auto Complete 2.0


Autocomplete Without JQuery UI And Ajax ToolKit
Autocomplete Without JQuery UI And Ajax ToolKit Demo


Popular Posts