Skip to main content

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++)
    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;
    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 + "'}";
    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() {

   }).mouseout(function() {
    $this.blur(function() {
 else {
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 = $; 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() {
function removCssLE() {
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') });

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; }

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 from this blog

Uploading large file in chunks in Mvc c# from Javascript ajax

Often we have a requirement to upload files in, Mvc c# application but when it comes to uploading larger file, we always think how to do it as uploading large file in one go have many challenges like UI responsiveness, If network fluctuate for a moment in between then uploading task get breaks and user have to upload it again etc.

regex - check if a string contains only alphabets c#

How to validate that input string contains only alphabets, validating that textbox contains only alphabets (letter), so here is some of the ways for doing such task. char have a property named isLetter which is for checking if character is a letter or not, or you can check by the regular expression  or you can validate your textbox through regular expression validator in Following code demonstrating the various ways of implementation.

Regular expression for alphanumeric with space in c#

How to validate that string contains only alphanumeric value with some spacial character and with whitespace and how to validate that user can only input alphanumeric with given special character or space in a textbox (like name fields or remarks fields). In remarks fields we don't want that user can enter anything, user can only able to enter alphanumeric with white space and some spacial character like -,. etc if you allow. Some of regular expression given below for validating alphanumeric value only, alphanumeric with whitspace only and alphanumeric with whitespace and some special characters.

How to validate dropdownlist in JavaScript

In this article you will see how to put validation in dropdownlist by javascript, suppose first item value of dropdownlist is 0 and text is "-Select-" just like given below and we have to validate that at least one item is selected excluding default i.e "-Select-".