I am Raghuveer

In my opinion programming means thinking, and it is fun. My vision is to teach programming in more understandable manner to the students from rural background. I support programming for everyone

Showing posts with label JQuery. Show all posts
Showing posts with label JQuery. Show all posts

Sorting ASP.NET GridView Control using JQuery Tablesorter Plugin

Displaying records in a tabular format is very common functionality of modern websites. Almost all the websites you visit these days have data to display in a table or datagrid and most of them also required the functionality of sorting records based on any column. Last week I had a chance to work with one of a popular JQuery plugin called Tablesorter and I was so impressed that I decided to write a full tutorial on it. In this tutorial, I will show you how you can use JQuery Tablesorter plugin with ASP.NET GridView control to provide client side sorting functionality to your site visitors.
Sorting ASP.NET GridView Control with JQuery Tablesorter Plugin
If you want to play with the Tablesorter JQuery plugin yourself with all the customized options, make sure you download the latest version ofTablesorter plugin from the following URL.
http://tablesorter.com/docs
Create a new ASP.NET website and drag a GridView control on the page. Disable the automatic columns generation by usingAutoGenerateColumns property and add some bound fields inside the GridView Columns collection. For this tutorial, make sure your GridView control HTML markup looks similar to the following:
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333"
GridLines="Horizontal" Font-Size="9pt" Font-Names="Arial"
AutoGenerateColumns="False" BorderColor="#dadada"
BorderStyle="Solid" BorderWidth="1px">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID"
ItemStyle-Width="40" />
<asp:BoundField DataField="Name" HeaderText="Name"
ItemStyle-Width="80" />
<asp:BoundField DataField="Fee" DataFormatString="{0:n0}" HeaderText="Fee"
ItemStyle-Width="60" />
<asp:BoundField DataField="Price" DataFormatString="{0:c}"
HeaderText="Price" ItemStyle-Width="60" />
<asp:BoundField DataField="Discount" DataFormatString="{0:p1}"
HeaderText="Discount" ItemStyle-Width="70" />
<asp:BoundField DataField="Difference" DataFormatString="{0:n1}"
HeaderText="Difference" ItemStyle-Width="80" />
<asp:BoundField DataField="Date" DataFormatString="{0:MMM dd, yyyy}"
HeaderText="Date" ItemStyle-Width="100" />
<asp:BoundField DataField="OnSale" HeaderText="OnSale"
ItemStyle-Width="60" />
</Columns>
</asp:GridView>
As you can see bound fields are bound with columns such as ID, Name, Fee and so on. These columns are coming from a temporary DataTable object which I have filled and bind with GridView in the Page Load event. Following code shows the Page Load event and the code required to fill DataTable.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
}
}
private void BindData()
{
int[] ids = {12, 13, 14, 15, 16};
string[] names = {"Alice", "James", "Peter", "Simon", "David"};
int[] fee = { 2299, 5123, 7564, 9595, 1600 };
decimal[] prices = { 12.99m, 122.23m, 25.64m, 66.85m, 1.60m };
decimal[] discounts = { 0.2m, 0.194m, 0.4564m, 0.209m, 0.310m };
decimal[] differences = { -12m, 19.4m, -45.64m, 200.9m, 41.60m };
string[] dates = { "04-12-2010", "07-23-2010", "07-14-2009", "12-12-2010", "11-03-2019" };
bool[] onSale = { true, false, true, true, false };
DataTable table = new DataTable();
table.Columns.Add("ID", typeof(System.Int32));
table.Columns.Add("Name", typeof(System.String));
table.Columns.Add("Fee", typeof(System.Decimal));
table.Columns.Add("Price", typeof(System.Decimal));
table.Columns.Add("Discount", typeof(System.Decimal));
table.Columns.Add("Difference", typeof(System.Int32));
table.Columns.Add("Date", typeof(System.DateTime));
table.Columns.Add("OnSale", typeof(System.Boolean));
for (int i = 0; i < 5; i++)
{
DataRow row = table.NewRow();
row["ID"] = ids[i];
row["Name"] = names[i];
row["Fee"] = fee[i];
row["Price"] = prices[i];
row["Discount"] = discounts[i];
row["Difference"] = differences[i];
row["Date"] = DateTime.Parse(dates[i]);
row["OnSale"] = onSale[i];
table.Rows.Add(row);
}
GridView1.DataSource = table;
GridView1.DataBind();
GridView1.UseAccessibleHeader = true;
GridView1.HeaderRow.TableSection = TableRowSection.TableHeader;
}

Before you build and test your web page, add the following CSS styles inside page head section to add some spice to your GridView.
<style type="text/css">
th
{
cursor:pointer;
background-color:#dadada;
color:Black;
font-weight:bold;
text-align:left;
}
th.headerSortUp
{
background-image: url(images/asc.gif);
background-position: right center;
background-repeat:no-repeat;
}
th.headerSortDown
{
background-image: url(images/desc.gif);
background-position: right center;
background-repeat:no-repeat;
}
td
{
border-bottom: solid 1px #dadada;
}
</style>

Add the following JQuery and Tablesorter javascript files references inside page head section.
<script src="scripts/jquery-1.4.3.min.js" type="text/javascript"></script>
<script src="scripts/jquery.tablesorter.min.js" type="text/javascript"></script>
Click here for table sorter plugin
Finally call the tablesorter function on GridView to make your GridVeiw sortable.
<script type="text/javascript">
$(document).ready(function() {
$("#GridView1").tablesorter();
});
</script>

You can see how easy is to add client side sorting functionality to your GridView using the Tablesorter plugin. You just need to call a single function Tablesorter to implement basic sorting. However, there are many other options to customize the sorting functionality, and I will recommend you to visit the Tablesorter plugin home page to read the documentation for all the available options.

ASP.NET GridView Mouseover Hover Effect using JQuery

JQuery API has many CSS related functions, which can be used to create many UI effects in the modern web applications. The most common of those methods are addClass, removeClass and toggleClass, which add, remove or toggle CSS classes to any matched element. In this Tutorial, I will show you how you can create a simple mouseover hover effect on ASP.NET GridView Rows using JQuery CSS related methods.

To get things started, create an ASP.NET website and add a GridView control to the page from the Data Category in Toolbox. The following code shows the GridView control I am using for the demonstration of this tutorial. Please set the appropriate properties as shown in the code snippet below.

<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" BackColor="White" Font-Size="10"
Font-Names="Verdana" BorderColor="#000000" BorderStyle="Solid" BorderWidth="1px"
CellPadding="3" Width="400px" CellSpacing="0" GridLines="Horizontal">
</asp:GridView>

</form>

Next I am binding the GridView with a DataTable object that I created in the Page Load event in the code behind file. To keep things simple I am not connecting any database as it is not the purpose of this tutorial. I created a DataTable object with three columns and filled it with some rows using for loop. The complete code of the Page Load event is shown below:

protected void Page_Load(object sender, EventArgs e)
{
DataTable table = new DataTable();
table.Columns.Add("ID", typeof(int));
table.Columns.Add("Name", typeof(string));
table.Columns.Add("Salary", typeof(decimal));
for (int i = 1; i < 8; i++)
{
DataRow row = table.NewRow();
row["ID"] = i;
row["Name"] = "Name " + i;
row["Salary"] = 10000 * i;
table.Rows.Add(row);
}
GridView1.DataSource = table;
GridView1.DataBind();
if (GridView1.Rows.Count > 0)
{
GridView1.UseAccessibleHeader = true;
GridView1.HeaderRow.TableSection = TableRowSection.TableHeader;

}
}

By default, The GridView control doesn’t render the <th> tags for the header row which can be an issue for sites where standard compliance and accessibility are important. When we set the property UseAccessibleHeader = true, it replaces the <td> elements of the header row with the correct <th> element. The HeaderRow.TableSection property of GridView control generates <thead> and <tbody> tags to make generated code more accessible. Build and run your project, and you will see the following output.

GridView without Highlighting

Although the above output looks very simple but the important thing to note is the HTML generated by the GridView control. Please check the source code of the page from the browser View Source option and see the HTML table code is generated. Next you need to add following CSS style rules inside the <head> section of the page. We will use the headerRow, highlightRow and selectedRow CSS classes in JQuery code in few minutes.

<style type="text/css">
th
{
text-align:left;
}
.headerRow
{
background-color: #000000;
color:White;
font-weight:bold;
}
.highlightRow
{
background-color: #dadada;
cursor: pointer;
border:solid 1px black;
}
.selectedRow
{
background-color: #808080;
cursor: pointer;
border:solid 1px black;
color:White;
}
</style>

Next add the JQuery script file reference inside the <head> section of the page depending on the script file location and JQuery version you are using.

<script src="scripts/jquery-1.4.3.min.js" type="text/javascript"></script>

Next add the following JQuery code inside a script block in<head>section of the page.

<script type="text/javascript">
$(document).ready(function () {
$('#GridView1 thead').addClass('headerRow');
$('#GridView1 tbody tr').mouseover(function () {
$(this).addClass('highlightRow');
}).mouseout(function () {
$(this).removeClass('highlightRow');
}).click(function () {
$(this).toggleClass('selectedRow');
});

});
</script>

The code defines typical JQuery ready method, which is used to access and manipulate DOM elements when they are loaded by the browser. The first line of code uses a JQuery selector to select<thead>section of the html table and adds a CSS class to the element using JQuery APIaddClass method.

$('#GridView1 thead').addClass('headerRow');

Next I am adding a sequence of three JQuery events mouseover, mouseout and click to the table rows<tr>elements.

$('#GridView1 tbody tr').mouseover(function () {
$(this).addClass('highlightRow');
}).mouseout(function () {
$(this).removeClass('highlightRow');
}).click(function () {
$(this).toggleClass('selectedRow');
});

Each one of these events takes a function handler as a parameter in which you can write code you want to execute when these events occur on table rows. I am using addClass method to add CSS class inside mouseover event handler and removing the same CSS class using theremoveClass method inside mouseout event handler. This will give you hover effect when you will move the mouse on table rows. The clickevent handler uses JQuery API toggleClass method which adds or removes CSS classes based on the class presence. You can read more about these methods at the following URL on JQuery website.
http://api.jquery.com/category/css
If you have followed the complete tutorial with me you will see the GridView with mouseover hover and click effects as shown in the following figure.

GridView with mouseover hover and click effect

I hope you have enjoyed this tutorial as much as I have enjoyed writing it. You can download the full source code of this tutorial by clicking theDownload Source Code button at the top of this page. You can also watch the live demo by clicking the Live Demo button.

Download Source Code

Calling ASP.NET Web Services using JQuery AJAX

AJAX has changed the way we developed web sites in the past by giving them responsiveness similar to Desktop applications. In Plain English, AJAX means that instead of waiting for the whole web page to load you can load and display only what you need to. Technically speaking, it’s a technique to communicate with servers through JavaScript asynchronously and handle external data. In this tutorial, I will show you how you can call ASP.NET web service using JQuery, which is the most popular and widely used JavaScript library.

To start communicating with ASP.NET web service through JQuery we first need to implement our web service. Create an ASP.NET web site project in Visual Studio and add an ASP.NET Web Service by right clicking the project name and choosing Add New Item option as shown in the figure below.

Add New Item Dialog

Once the Add New Item dialog box appears, select Web Service (.asmx) item from the list and give web service a suitable name such asDateWebService.asmx. Visual Studio will create a web service (.asmx) and related code behind files in the project. You need to add a method GetDateTime in web service code behind file but keep in mind that we will call this web service from JavaScript so you need to remove comments from the attribute System.Web.Script.Services.ScriptService of your class. The complete code of the web service class is shown below.

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class DateWebService : System.Web.Services.WebService {
public DateWebService () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string GetDateTime() {
return DateTime.Now.ToString();
}

}


The web service code is pretty straight forward as there is only one method GetDateTime defined returning the current Date and Time using DateTime.Now property. Before calling the service method using JQuery you need to keep in mind few restrictions on calling service methods from JavaScript. To preventing some security vulnerabilities, ASP.NET service validation layer checks for following two things when service methods are called from JavaScript.

  1. Only POST method can be used to call a web service method. You cannot use HTTP GET.
  2. The HTTP content-type header should be set to the value "application/json".
For those of you who are not familiar with JSON may be wondering what is json and where it came from. So don’t worry I have some basic introduction for you in this tutorial as we will use it in few minutes using JQuery AJAX. In modern AJAX based web applications, when web services are called from client applications, they normally return XML formatted response, which can be parsed and use in JavaScript, but it complicates things for developers. They need a simple data structure which can be used more easily than XML. This is where JavaScript Object Notation (JSON) comes to help us with the following major features.
  1. Lightweight data-interchange format.
  2. Easy for humans to read and write.
  3. Easy for machines to parse and generate.
  4. JSON can be parsed trivially using the JavaScript eval() procedure or using some useful methods in JQuery API.
  5. JSON supports almost all modern languages such as ActionScript, C, C#, ColdFusion, Java, JavaScript, Perl, PHP, Python, Ruby and many more.

Any .NET object you return from web service methods can be serialized in JSON format. To get some familiarity with JSON format, let’s say you have following custom Product object initialized with some properties.

Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };


If you will serialize the object in JSON format it will produce the following output:

{
"Name": "Apple",
"Expiry": new Date(1230422400000),
"Price": 3.99,
"Sizes": [
"Small",
"Medium",
"Large"
]
}


You can see from the above output that JSON data structure is very easy to read and understand. If you are a .NET developer and want to learn more about serialization and de-serialization of .NET objects into JSON, I will recommend you to use free JSON.NET library available atjson.codeplex.com.
Let’s come back to our tutorial, we have implemented web service so it’s time to create a web page and call that service using JQuery. Create an ASP.NET web form (.aspx) in your project and add the following button and span tag in web form.

<form id="form1" runat="server">
<input id="Button1" type="button" value="Get Date and Time" />
<br />
<br />
<span id="output" />
</form>


Next add the JQuery library reference and the following JQuery script in the head section of the page.

<script src="Scripts/jquery-1.4.3.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#Button1").click(function() {
$.ajax({
type: "POST",
url: "/ASPNET_WebServices_JQuery/DateWebService.asmx/GetDateTime",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg)
{
$("#output").text(msg.d);
}
});

});
});
</script>

The important lines in the above code are when the $.ajax() method is called inside the Button1 click event handler. $.ajax() method performs an asynchronous HTTP AJAX request and can be customized with many parameters. Some of the parameters I used in the above code are explained below:
type: The type of request you want to make "POST" or "GET". The default value of this parameter is "GET"
url: A string containing the URL to which the request is sent. In the code above, I put the website project name followed by the service file name with extension and then the web method name.
data: This parameter contains the data to be sent to the server. For the GET requests it will be appended to the url although you can change this behavior using processData parameter (not used in the above example). I am using empty braces in the above example as I am not passing any parameters to service methods.
contentType: When sending data to the server, use this content-type. Default is "application/x-www-form-urlencoded". Data will always be transmitted to the server using UTF-8 charset. In the above code, I am explicitly using application/json as the contentType.
dataType: The type of data that you're expecting back from the server. If none is specified, JQuery will intelligently try to get the results, based on the MIME type of the response. The available types are xml, html, script, json, jsonp and text.
success: JQuery $.ajax() method also supports many callback functions, which are invoked at the appropriate during the request process. One of them is a success which is called if the request succeeds.
In this tutorial, I have explained all the options used in this example code above but there are more parameters and options available, and If you are interested to read more about JQuery $.ajax() method please visit the JQuery API documentation available athttp://api.jquery.com/jQuery.ajax.
Build and test your page in the browser, and you will see the server time displayed on the page when you will click the button. If you are using FireFox you can even see the JSON formatted response came from the server in my favorite FireFox plug-in Firebug.

JQuery AJAX ASPNET Web Service

In this tutorial, I tried to give you the basic introduction of calling ASP.NET web service using JQuery AJAX along with some explanation of JSON format. In my future tutorials, I will show you more complex interaction between client and server using JQuery AJAX so please keep visiting my website to learn more about the tips and tricks of latest technologies.

Download Source Code

Select Deselect GridView Rows using a Checkbox in JQuery

Many websites require functionality for letting their site visitors to select and deselect all the rows in GridView using a single checkbox normally available in the header row. You may have seen the examples of such functionality in Yahoo Mail or Hotmail inbox where you can select all the emails by clicking the single Checkbox on top of the email's grid. In this tutorial, I will show you how you can provide this functionality in ASP.NET GridView control using few lines of JQuery code.

Select Unselect GridView Rows

To get started, create an ASP.NET website and drag a GridView control on the page. For this tutorial, I am using ID, Name and Salary columns, so I added three bound fields and one TemplateField that will contain the checkboxes in the header as well as in the individual row. Following is the complete HTML source for the GridView control.

<asp:GridView ID="GridView1" runat="server" Font-Size="10pt"
Font-Names="Verdana" CellPadding="4" Width="400px" GridLines="None"
ForeColor="#333333" AutoGenerateColumns="false">
<RowStyle BackColor="#EFF3FB" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkHeader" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkRow" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ID" HeaderText="ID" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Salary" HeaderText="Salary" />
</Columns>
</asp:GridView>

To keep this tutorial simple, I am not connecting my GridView with the database and showing some sample data in the GridView. Add the following code in the Page Load event of the page to add few rows of data.

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadData();
}
}
private void LoadData()
{
DataTable table = new DataTable();
table.Columns.Add("ID", typeof(int));
table.Columns.Add("Name", typeof(string));
table.Columns.Add("Salary", typeof(decimal));
for (int i = 1; i < 8; i++)
{
DataRow row = table.NewRow();
row["ID"] = i;
row["Name"] = "Name " + i;
row["Salary"] = 10000 * i;
table.Rows.Add(row);
}
GridView1.DataSource = table;
GridView1.DataBind();
}


Now we need only few lines of JQuery code to provide the functionality of selecting or deselecting rows using the checkbox added in the header of the GridView. Add the JQuery script file reference in the head element of the page.

<script src="scripts/jquery-1.4.3.min.js" type="text/javascript"></script>
Add the following JavaScript block inside the head element of the page.
<script type="text/javascript">
$(document).ready(function() {
var headerCheckbox = $('#GridView1 > tbody > tr > th > input:checkbox');
headerCheckbox.click(function() {
var headerChecked = $(this).attr('checked');
var rowCheckboxes = $('#GridView1 > tbody > tr > td > input:checkbox');
rowCheckboxes.attr('checked', headerChecked);
});

});
</script>


The above code is using typical JQuery ready function to add some JQuery statements or code. The first line access the checkbox available in the header row of the GridView using JQuery selector.
var headerCheckbox = $('#GridView1 > tbody > tr > th > input:checkbox');
Once we have the reference of header checkbox, we are using the click event function handler that will allow us to run some code every time user will click the header checkbox. Inside click event function handler, the first line stores the current state of the header checkbox in aheaderChecked variable. The second line gets the reference of all the checkboxes in all the rows in GridView and then set their state to the same state as the header checkbox using JQuery attr function.

headerCheckbox.click(function() {
var headerChecked = $(this).attr('checked');
var rowCheckboxes = $('#GridView1 > tbody > tr > td > input:checkbox');
rowCheckboxes.attr('checked', headerChecked);
});


Build and test your web page and click the checkbox in the header row, and you will be able to select or deselect all checkboxes in GridView rows. You can click the Live Demo button to see the working example of this tutorial.

Download Source Code Download Source Code Live Demo Live Demo

Using ASP.NET AJAX ModelPopupExtender from Client Side

Model dialog boxes are very common these days not only in Windows applications but also in web applications. They allow web developers to open new popup windows on the same page without creating a new web page. These popup windows typically ask user some input and temporarily disable the page unless the user dismisses the dialog box. ASP.NET developers can use ModelPopupExtender control available in ASP.NET AJAX controls toolkit to implement model dialog behavior in their web applications. In this tutorial, I will show you how you can use ModelPopupExtender control with client side behavior so that when user performs any action in the dialog box such as button click there is no post back to the server.

AJAX Model Popup Extender

Create a new web site in Visual Studio and open the page in which you want to use ModelPopupExtender control. The first thing you need to add is a CSS class which I will attach with ModelPopupExtender control to make page background transparent and little darker when theModelPopupExtender control will appear on screen. So add this CSS in your page header tag.

<style type="text/css">
.BackgroundStyle
{
background-color: #f3f3f3;
filter: alpha(opacity=50);
opacity: 0.5;
}
</style>

In this tutorial, I want to handle the button clicks inside ModelPopupExtender from client side so I also need a JavaScript function which I will attach with ModelPopupExtender later in this tutorial. Inside my page header tag add the following JavaScript markup.

<script type="text/javascript">
var language = "";
function SetLanguage(value)
{
language = value;
}
function OkButtonClick()
{
$get("Label1").innerHTML = language;
}
</script>

Next, we are moving to our page and you need to add ScriptManager control first which is required to use any ASP.NET AJAX related feature on the page.<asp:ScriptManager ID="ScriptManager1" runat="server" />
Next add a button and a label control on the page. The button will ask user to participate in a quick poll which will be shown in model dialog box and when user will submit the poll by clicking the submit button inside model dialog I will show the results on the label control.

<asp:Button ID="Button1" runat="server" Text="Quick Poll" />
<br />
<asp:Label ID="Label1" runat="server"></asp:Label>
Next you need to add a Panel control which will be used as a popup window by the ModelPopupExtender control.<asp:Panel ID="Panel1" runat="server" BackColor="#ffffff"
BorderColor="#dadada" BorderStyle="Solid" BorderWidth="4px"
Height="190px" Width="350px" Font-Names="Arial" Font-Size="10pt">
<table cellpadding="10" cellspacing="0" style="width: 100%">
<tr>
<td>
What is your Favorite Programming Language?
</td>
</tr>
<tr>
<td>
<input name="rdLanguage" type="radio" value="Java"
onclick="SetLanguage('Java');" />Java
<br />
<input name="rdLanguage" type="radio" value="VB.NET"
onclick="SetLanguage('VB.NET');" />VB.NET
<br />
<input name="rdLanguage" type="radio" value="C#"
onclick="SetLanguage('C#');" />C#
<br />
</td>
</tr>
<tr>
<td>
<asp:Button ID="Button2" runat="server" Text="Submit" />
<asp:Button ID="Button3" runat="server" Text="Cancel" />
</td>
</tr>
</table>
</asp:Panel>

The above markup inside Panel control is very straight forward. It has three radio button controls and two buttons arranged inside the html table for better layout. The only important thing to notice is how the SetLanguage method defined in the JavaScript above is called from the radio buttons onclick events. This is to set the language variable according to the radio button clicked. Each radio button is setting the language variable according to its own value.

<input name="rdLanguage" type="radio" value="Java"
onclick="SetLanguage('Java');" />
Finally, you need to add the ModelPopupExtender control available in ASP.NET AJAX controls toolkit as follows:<ajax:ModalPopupExtender ID="ModalPopupExtender1" runat="server"
TargetControlID="Button1"
PopupControlID="Panel1"
DropShadow="True"
CancelControlID="Button3"
OkControlID="Button2"
OnOkScript="OkButtonClick()"
BackgroundCssClass="BackgroundStyle" />

The following section explains all the ModelPopupExtender properties in detail:

TargetControlID:
This property needs the id of the target control that will activate the model popup dialog box. I have given the id of the first button control “Button1”.

PopupControlID:
This property needs the id of the control you want to use as a popup window. I have given the reference of the Panel control which ModelPopupExtender will display on screen.

DropShadow:
A Boolean property to add drop shadow to the popup window. I set it to true and you can see a black shadow with popup window in the figure above.

OkControlID:
This property needs the id of the control which will dismiss the model popup dialog box. I have given the reference of Submit Button here because I want the model popup to disappear automatically on Submit button click.

CancelControlID:
This property needs the id of the control that will cancel or dismiss the popup dialog box.

OnOkScript:
This property needs the name of the JavaScript function that will be called automatically when the modal popup is dismissed with the OkControlID. I have given the name of the JavaScript function I defined above so the code in the JavaScript function will run on Submit button click and will set the value of the Label control accordingly.

OnCancelScript:
This property needs the name of the JavaScript function that will be called automatically when modal popup is dismissed with the CancelControlID. In the example above I haven’t used this property because I don’t want to run any script on Cancel button click.
BackgroundCssClass:
This property needs the name of the CSS class to apply to the page background when the modal popup is displayed. I have given the name of the CSS class we defined in the start.

PopupDragHandleControlID:
This property needs the ID of the control which will be used to drag the popup dialog box on screen. Normally, this control is available at the top of the popup window and acts as a title bar for dragging operation. I have not used this property in this tutorial but you can provide dragging feature by setting this property in your applications.

X:
This property can be used to position the model dialog box on screen horizontally by setting the X coordinate of the top/left corner of the modal popup. If you will skip this property the model dialog box will appear centered horizontally.

Y:
This property can be used to position the model dialog box on screen vertically by setting the Y coordinate of the top/left corner of the modal popup. If you will skip this property the model dialog box will appear centered vertically.

RepositionMode:
This property determines whether the popup needs to be repositioned when the window is resized or the page is scrolled by the user.

Creating Popup Dialog Windows using JQuery

source: ezzylearning

If you are a regular internet user and specially visit sites like Facebook, Twitter, Yahoo Mail, I am sure you are familiar with the popup dialog windows appears on the screen asking you different options or display information or warning messages. Popup dialog windows are child windows and commonly used in GUI systems and User Interface designs to interact with the user without disturbing the main application or window workflow. In this tutorial, I will show you how you can create simple and modal popup dialog windows using JQuery.

JQuery Modal Popup Dialog

 

Before I start this tutorial, I assume that you are familiar with HTML, CSS and JavaScript, and if you are not then please visitwww.w3schools.com for some easy tutorials. I also assume that you know what JQuery is and how to use it in your web pages. I will recommend you to read my other JQuery tutorials on this website to learn the basics of JQuery. You can also visit www.jquery.com to learn and download the latest version of JQuery.
The first thing you need is the basic HTML code to create a popup dialog box. Most developers normally use HTML div element to create floating dialog windows. Following is the HTML code I have used in this tutorial to create buttons and popup dialog windows shown in the above figure.

 

<h3>JQuery Popup Dialogs</h3>
<input type="button" id="btnShowSimple" value="Simple Dialog" />
<input type="button" id="btnShowModal" value="Modal Dialog" />
<br /><br />
<div id="output"></div>
<div id="overlay" class="web_dialog_overlay"></div>
<div id="dialog" class="web_dialog">
<table style="width: 100%; border: 0px;" cellpadding="3" cellspacing="0">
<tr>
<td class="web_dialog_title">Online Survey</td>
<td class="web_dialog_title align_right">
<a href="#" id="btnClose">Close</a>
</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr>
<td colspan="2" style="padding-left: 15px;">
<b>Choose your favorite mobile brand? </b>
</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr>
<td colspan="2" style="padding-left: 15px;">
<div id="brands">
<input id="brand1" name="brand" type="radio" checked="checked" value="Nokia" /> Nokia
<input id="brand2" name="brand" type="radio" value="Sony" /> Sony
<input id="brand3" name="brand" type="radio" value="Motorola" /> Motorola
</div>
</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr>
<td colspan="2" style="text-align: center;">
<input id="btnSubmit" type="button" value="Submit" />
</td>
</tr>
</table>
</div>

 

In the above HTML code, there are two important elements. The first element is the div tag with the id "overlay". This div will cover the entire page width and height to create a semi-transparent background when the popup dialog window will appear on the screen.

The second important element is the div tag with the id "dialog". This div will be used as popup dialog and can contain any type of HTML inside. I put an HTML table and created a simple online survey for this tutorial.

<div id="dialog" class="web_dialog">
...
</div>

You may have noticed that the HTML code shown above is using the CSS classes web_dialog_overlay, web_dialog, web_dialog_title etc. Following is the CSS code for all the classes I used in this tutorial.

<style type="text/css">
.web_dialog_overlay
{
   position: fixed;
   top: 0;
   right: 0;
   bottom: 0;
   left: 0;
   height: 100%;
   width: 100%;
   margin: 0;
   padding: 0;
   background: #000000;
   opacity: .15;
   filter: alpha(opacity=15);
   -moz-opacity: .15;
   z-index: 101;
   display: none;
}
.web_dialog
{
   display: none;
   position: fixed;
   width: 380px;
   height: 200px;
   top: 50%;
   left: 50%;
   margin-left: -190px;
   margin-top: -100px;
   background-color: #ffffff;
   border: 2px solid #336699;
   padding: 0px;
   z-index: 102;
   font-family: Verdana;
   font-size: 10pt;
}
.web_dialog_title
{
   border-bottom: solid 2px #336699;
   background-color: #336699;
   padding: 4px;
   color: White;
   font-weight:bold;
}
.web_dialog_title a
{
   color: White;
   text-decoration: none;
}
.align_right
{
   text-align: right;
}
</style>

There are few important things to explain in the above CSS code. Note how the .web_dialog_overlay class top, right, bottom, left, height and width properties are set to make sure it covers the entire browser display area. Furthermore, notice how the transparency is set using opacity, -moz-opacity and filter properties. In the .web_dialog class the important properties are width, height, top, left, margin-left and margin-top which are set appropriately to make sure the popup dialog appears in the center of the screen. You can play with these properties to display popup dialog anywhere you want. The display property for both classes is set to none to keep both div elements hidden. Another important property is the z-index which sets the stack order of different elements on the screen. The element with the greater stack order will always be in front of the elements with the lower stack order.

Now I am moving to the important JQuery and JavaScript code which will show you how to show/hide popup dialog windows using JavaScript and JQuery. You make sure you have included the required JQuery library reference in the head element of your page.

<script src="scripts/jquery-1.4.3.min.js" type="text/javascript"></script>

<script type="text/javascript">
   $(document).ready(function ()
   {
      $("#btnShowSimple").click(function (e)
      {
ShowDialog(false);
         e.preventDefault();
      });
      $("#btnShowModal").click(function (e)
      {
ShowDialog(true);
         e.preventDefault();
      });
      $("#btnClose").click(function (e)
      {
HideDialog();
         e.preventDefault();
      });
      $("#btnSubmit").click(function (e)
      {
         var brand = $("#brands input:radio:checked").val();
         $("#output").html("<b>Your favorite mobile brand: </b>" + brand);
HideDialog();
         e.preventDefault();
      });
   });
function ShowDialog(modal)
   {
      $("#overlay").show();
      $("#dialog").fadeIn(300);
      if (modal)
      {
         $("#overlay").unbind("click");
      }
      else
      {
         $("#overlay").click(function (e)
         {
            HideDialog();
         });
      }
   }
   function HideDialog()
   {
      $("#overlay").hide();
      $("#dialog").fadeOut(300);
   }

</script>

In the above code, there are two JavaScript functions ShowDialog() and HideDialog() defined to show/hide both transparent overlay div and dialog window. The ShowDialog function also has conditional code to implement simple or modal dialog windows. If you are displaying the modal window then clicking the overlay div will not hide the dialog box, and user has to close the popup window using the Submit button or Close link on top. These two functions are called from different button click events in the JQuery ready method. Finally there is a click event handler forbtnSubmit which display the user favorite mobile brand in output div element.

LIVE DEMO