jQuery Autosuggest Textbox

Want something other than dropdownlist? How about providing a fully responsive autosuggest textbox that quickly responses to every letter or character that you type? Yes it is possible with ASP.NET, with the help of my favourite language (C#) and jQuery.

The Process.

1. On page load, fetch all the data that needs to be listed, for example, cities, countries, product categories, products.
2. Load the data in an array in javascript through JSON.
3. In every character that you input in your textbox, match it with every word in your array with regards to the position of the character.
4. Display all the items that matched your criteria in the textbox.

The Architecture.

Web Form                         Generic Handler        Business Object Layer/Helper Class           Data Layer

process

The Logic Behind Each Process.

Web Form


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
 <title>Untitled Page</title>

 <script src="suggestions.js" type="text/javascript"></script>

 <script src="autosuggest.js" type="text/javascript"></script>

 <script src="jquery.js" type="text/javascript"></script>

 <script language="javascript" type="text/javascript">
 var modelArray = new Array();
 $(window).load(function(){
 $.getJSON("ProductsHandler.ashx", function(result) {
 var pos = 0;
 $.each(result, function() {
 modelArray[pos] = this['cnmodelname'];
 pos = pos + 1;
 });

 });
 });
 $(document).ready(function() {

 $("#txtProducts").focus(function() {
 var oTextbox=new AutoSuggestControl(document.getElementById("txtProducts"),new ProductsSuggestions());
 });
 });

 </script>

 <style>
 div.suggestions
 {
 -moz-box-sizing: border-box;
 box-sizing: border-box;
 border: 1px solid #cccccc;
 position: absolute;
 }
 div.suggestions div
 {
 cursor: default;
 padding: 0px 3px;
 }
 div.suggestions div.current
 {
 background-color: #3366cc;
 color: white;
 }
 </style>
</head>
<body style="margin-top: 100; margin-left: 100;">
 <form id="form1" runat="server">
 <div>
 <input type="text" id="txtProducts" />
 </div>
 </form>
</body>
</html>

Generic Handler


using System;
using System.Data;
using System.Text;
using System.Web;

namespace TestWebApplication {

public class ProductsHandler : IHttpHandler {

public void ProcessRequest(HttpContext context) {

string results = "";

Products p = new Products();
DataTable dt = p.GetCurrentProducts();
StringBuilder sb = new StringBuilder();
sb.Append("[");
foreach (DataRow item in dt.Rows) {
sb.Append("{");
sb.Append("\"cnmodelid\":\""+item["cnmodelid"].ToString()+"\",");
sb.Append("\"cnmodelname\":\"" + item["cnmodelname"].ToString() + "\"");
sb.Append("},");
}
results = sb.ToString();
results = results.Remove(results.Length - 1, 1) + "]";

context.Response.ContentType = "application/json";
context.Response.ContentEncoding = Encoding.UTF8;
context.Response.Write(results);
context.Response.End();
}

public bool IsReusable {
get {
return false;
}
}
}
}

Business Object Layer/Helper Class


using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;

namespace TestWebApplication {

public class Product  {
DataLayer dal;
public Product() {
dal = new DataLayer();
}

public DataTable GetCurrentProducts() {
using (SqlCommand sqlCommand = new SqlCommand()) {
sqlCommand.CommandText = "sp_GetProducts";
sqlCommand.CommandType = CommandType.StoredProcedure;

return dal.GetRecords(sqlCommand);
}
}
}
}

Data Layer


using System;
using System.Data;
using System.Data.SqlClient;

namespace TestWebApplication {
public class DataLayer {

public DataTable GetRecords(SqlCommand sqlCommand) {
using (SqlConnection sqlCon = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=OnlineBackupApplication;User Id=constantine;Password=100885101#;")) {
sqlCon.Open();
SqlCommand sqlCmd = sqlCommand;
sqlCmd.Connection = sqlCon;
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);

DataTable dtLocal = new DataTable();
sqlDa.Fill(dtLocal);
sqlCon.Close();
return dtLocal;
}
}

}
}

Our Records

data

Our Output

data2

Note:

Please download this scripts from this site. http://www.phpguru.org/static/AutoComplete.html
1. suggestions.js
2. autosuggest.js

Changes Made to suggestions.js

1. Added the below functions to get the exact location of our textbox.

</pre>
function getAbsolutePosition(element){
 var ret = new Point();
 for(;
 element && element != document.body;
 ret.translate(element.offsetLeft, element.offsetTop), element = element.offsetParent
 );

 return ret;
}

function Point(x,y){
 this.x = x || 0;
 this.y = y || 0;
 this.toString = function(){
 return '('+this.x+', '+this.y+')';
 };
 this.translate = function(dx, dy){
 this.x += dx || 0;
 this.y += dy || 0;
 };
 this.getX = function(){ return this.x; }
 this.getY = function(){ return this.y; }
 this.equals = function(anotherpoint){
 return anotherpoint.x == this.x && anotherpoint.y == this.y;
 };
}

Changes Made to autosuggest.js

1. Changed getLeft function to the following block of code.


AutoSuggestControl.prototype.getLeft = function () {
var iLeft = getAbsolutePosition(document.getElementById("txtProducts")).x;
return iLeft;
};

2. Changed getTop function to the following block of code.


AutoSuggestControl.prototype.getTop = function () {
var iTop = getAbsolutePosition(document.getElementById("txtProducts")).y;
return iTop;
};

[/sourcecode]

Advertisements

2 thoughts on “jQuery Autosuggest Textbox

Add yours

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

Up ↑

%d bloggers like this: