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

Creating a modal message box in jQuery

One of the common tasks of web developers is to develop and design their site according to its purpose. And in-order for their sites to look more professional, the theme of the site, the animations, banners, buttons, fonts, links should be uniform. For example the font of a link button must be the same with the font of the content.

In this article, I am going to show you how to create a modal dialog using jQuery instead of showing the usual pop-up message of your web browser. First lets take a look at the common way of doing it.

The usual style.

<script language=”javascript” type=”text/javascript”>

function ShowModalBox() {

alert(“The common box”);

}

</script>

<input type=”button” value=”Show Modal Box” onclick=”ShowModalBox();” />

The output.

second

The jQuery way of  doing it.

<script language=”javascript” type=”text/javascript”>
$().ready(function() {
$(“#btnShowModalBox”).click(function() {

$(“#Container”).css(“visibility”,”visible”);
$(“#Container”).css(“float”,”none”);
$(“#Container”).css(“position”,”absolute”);
$(“#Container”).css(“left”,0);
$(“#Container”).css(“top”,0);
$(“#Container”).css(“width”,window.screen.width);
$(“#Container”).css(“height”,window.screen.height);
$(“#Container”).css(“background-color”,”#555555″);
$(“#Container”).css(“opacity”,”0.5″);

var left = window.screen.width / 2 – 200;
var top = window.screen.height / 2 – 300;
$(“#PopupBox”).css(“visibility”,”visible”);
$(“#PopupBox”).css(“float”,”none”);
$(“#PopupBox”).css(“position”,”absolute”);
$(“#PopupBox”).css(“left”,left);
$(“#PopupBox”).css(“top”,top);

});
$(“#btnClose”).click(function() {
$(“#PopupBox”).css(“visibility”,”hidden”);
$(“#Container”).css(“visibility”,”hidden”);
});
});
</script>

<body style=”margin: 50px; font-family: Verdana; font-size: 11px; font-weight: bold;”>
<form id=”form1″ runat=”server”>
<div style=”float: left; position: relative; width: 100%;”>
<input type=”button” id=”btnShowModalBox” value=”Show Modal Box” />
</div>
<div id=”PopupBox” style=”width: 400px; height: 300px; visibility: hidden; z-index: 1;”>
<div style=”float: left; position: relative; height: 20px; background-color: navy;
width: 365px; color: #ffffff; padding-left:5px; padding-top:5px;”>
JQuery Modal Dialog
</div>
<div style=”float: left; position: relative; height: 20px; background-color: navy;
width: 30px; color: #ffffff; padding-top:5px; text-align:center;”>
<input type=”button” id=”btnClose” value=”x” style=”border-style:solid; border-width:1px; background-color:#ffffff; height:15px; padding:0px; cursor:pointer;” />
</div>
<div style=”float: left; position: relative; background-color: #ffffff; width: 400px;
height: 150px;text-align: center; vertical-align:middle;”>
This is how to implement a simple Modal Dialog
</div>
</div>
<div id=”Container” style=”visibility: hidden; z-index: 0;”>
</div>
</form>
</body>

The output.

jqueryoutput

If you’ll notice there is now a gray background on top of our page where our dialog box is aligned in the middle.

How did we achieve that?

I. We must first create our dialog box.

jqueryoutputBox

Here is the code for the message box.

<body style=”margin: 50px; font-family: Verdana; font-size: 11px; font-weight: bold;”>
<form id=”form1″ runat=”server”>
<div style=”float: left; position: relative; width: 100%;”>
<input type=”button” id=”btnShowModalBox” value=”Show Modal Box” />
</div>
<div id=”PopupBox” style=”width: 400px; height: 300px; visibility: hidden; z-index: 1;”>
<div style=”float: left; position: relative; height: 20px; background-color: navy;
width: 365px; color: #ffffff; padding-left:5px; padding-top:5px;”>
JQuery Modal Dialog
</div>
<div style=”float: left; position: relative; height: 20px; background-color: navy;
width: 30px; color: #ffffff; padding-top:5px; text-align:center;”>
<input type=”button” id=”btnClose” value=”x” style=”border-style:solid; border-width:1px; background-color:#ffffff; height:15px; padding:0px; cursor:pointer;” />
</div>
<div style=”float: left; position: relative; background-color: #ffffff; width: 400px;
height: 150px;text-align: center; vertical-align:middle;”>
This is how to implement a simple Modal Dialog
</div>
</div>

<div id=”Container” style=”visibility: hidden; z-index: 0;”>
</div>
</form>
</body>

II. Then our gray background which will cover the entire page.

<body style=”margin: 50px; font-family: Verdana; font-size: 11px; font-weight: bold;”>
<form id=”form1″ runat=”server”>
<div style=”float: left; position: relative; width: 100%;”>
<input type=”button” id=”btnShowModalBox” value=”Show Modal Box” />
</div>
<div id=”PopupBox” style=”width: 400px; height: 300px; visibility: hidden; z-index: 1;”>
<div style=”float: left; position: relative; height: 20px; background-color: navy;
width: 365px; color: #ffffff; padding-left:5px; padding-top:5px;”>
JQuery Modal Dialog
</div>
<div style=”float: left; position: relative; height: 20px; background-color: navy;
width: 30px; color: #ffffff; padding-top:5px; text-align:center;”>
<input type=”button” id=”btnClose” value=”x” style=”border-style:solid; border-width:1px; background-color:#ffffff; height:15px; padding:0px; cursor:pointer;” />
</div>
<div style=”float: left; position: relative; background-color: #ffffff; width: 400px;
height: 150px;text-align: center; vertical-align:middle;”>
This is how to implement a simple Modal Dialog
</div>
</div>

<div id=”Container” style=”visibility: hidden; z-index: 0;”>
</div>

</form>
</body>

III. Finally our jQuery Code

// jQuery has a simple statement that checks the document and waits until it’s ready to be manipulated, known as the ready event

$().ready(function() {

}

//Then we assign a click event for our btnShowModalBox button

$().ready(function() {
$(“#btnShowModalBox”).click(function() {

});

});

//Then we manipulate the position,visibility, width and height of our gray message box container.

$(“#Container”).css(“visibility”,”visible”); -> sets the visibility of our div to visible which is initially hidden.
$(“#Container”).css(“float”,”none”);  -> sets the float property
$(“#Container”).css(“position”,”absolute”); -> sets the position and assign aabsolute value
$(“#Container”).css(“left”,0);  -> sets the left property
$(“#Container”).css(“top”,0); -> sets the top property
$(“#Container”).css(“width”,window.screen.width); -> sets the width of our div
$(“#Container”).css(“height”,window.screen.height); -> sets the height of our div
$(“#Container”).css(“background-color”,”#555555″); -> sets the background color
$(“#Container”).css(“opacity”,”0.5″); -> sets the opacity of our gray background to half

//And then we show our message box

var left = window.screen.width / 2 – 200;
var top = window.screen.height / 2 – 300;
$(“#PopupBox”).css(“visibility”,”visible”);
$(“#PopupBox”).css(“float”,”none”);
$(“#PopupBox”).css(“position”,”absolute”);
$(“#PopupBox”).css(“left”,left);
$(“#PopupBox”).css(“top”,top);

//Finally to hide our box we assign a click event to our button located on the upper right-most of the message box.

$(“#btnClose”).click(function() {
$(“#PopupBox”).css(“visibility”,”hidden”); -> hides the messagebox
$(“#Container”).css(“visibility”,”hidden”);-> hides the gray area
});

And that is how we create a simple modal message box using jQuery.  You can even make the message box fade by using the bellow function in jQuery.

$("#PopupBox").fadeIn("slow");