Building a Custom Confirmation Dialog Box
 
Published: 27 Aug 2007
Abstract
In this article Haissam Abdul Malak will show how you can create your own custom confirmation message to be used instead of the browser's default confirmation dialog and the purpose behind it.
by Haissam Abdul Malak
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 102020/ 375

Introduction

Who has not used the window.confirm() method to display a confirmation dialog box to the user before continuing the processing on the server side? I actually loved that dialog box when I first started using it; however, two annoying things were pushing me to create my own custom dialog.

·         Default button focus: The default selected button is "OK." Consider that you have a grid control and a delete button on its rows to allow the user to delete a certain row and on the delete button click event you would like to show a confirmation message. It is good practice to show such a dialog box in such operations. However, if the user clicks by mistake the enter keyboard key, the OK button click event is handled.

·         Default Buttons: The two default buttons are OK and Cancel and they cannot be modified.

The benefits for using this custom dialog box are as follows:

·         The need to set a default button to a different control other than the OK button.

·         The need to change the text for the buttons to a value different than the default ones used by the web browser (in this example I have used Yes and No), and finally, the need to change its appearance.

One last thing I should mention is the ability of this dialog box to re-locate itself once the window is resized. In this way the dialog box will always appear in the center of the window.

Procedure

Let us now examine the procedure to create a custom dialog box.

HTML code

This dialog box consists of the below controls.

1. Three div layers

2. Two web server controls (buttons)

Listing 1

<div id="divConfMessage" runat="server" style="BORDER-RIGHT:black thin solid; 
BORDER-TOP:black thin solid; DISPLAY:none; Z-INDEX:200; 
BORDER-LEFT:black thin solid; BORDER-BOTTOM:black thin solid">
  <div style="BACKGROUND-COLOR: #6699cc;TEXT-ALIGN: center" id="confirmText">
  </div>
  <div style="Z-INDEX: 105;HEIGHT: 2%;BACKGROUND-COLOR: white;TEXT-ALIGN: center">
  </div>
  <div style="Z-INDEX: 105;BACKGROUND-COLOR: white;TEXT-ALIGN: center">
    <asp:Button ID="btnConfOK" Runat="server" Text="OK"></asp:Button>
    <asp:Button ID="btnConfCancel" Runat="server" Text="Cancel"></asp:Button>
  </div>
</div>

The above listing will create a div layer which will serve as our dialog box. This layer, hidden by default, contains another div layer "confirmText" used to set the message to the user and another div layer containing the two buttons used.

Note that in the style attribute of each div layer we are setting the Z-INDEX property to a value (higher than all the z-index of other controls on the page) to make all the div layers appear on top of all controls.

JavaScript Code

In this section we will create a javascript file containing 4 global variables and 5 functions.

1. Global variables

          a - var divWidth = ''; this variable is used to set the dialog box width.

          b - var divHeight = ''; this variable is used to set the dialog box height.

          c - var txtFirstButton = OK; this variable is used to set the text of the first button.

          d- var txtSecondButton = Cancel; this variable is used to set the text of the second

               button.

2. Functions

          a - DisplayConfirmMessage(msg,width,height)

          b- SetTopLeft(divLayer)

          c- SetHeightWidth(divLayer)

          d- SetText(txtButton1,txtButton2)

          f - SetDefaultButton(defaultButton)

Listing 2

function DisplayConfirmMessage(msg, width, height)
{
  // Set default dialogbox width if null
  if (width == null)
  divWidth = 180
  else
    divWidth = width;
 
  // Set default dialogBox height if null
  if (height == null)
  divHeight = 90
  else
    divHeight = height;
 
 
  // Ge the dialogbox object
  var divLayer = document.getElementById('divConfMessage');
  // Set dialogbox height and width
  SetHeightWidth(divLayer)
  // Set dialogbox top and left
  SetTopLeft(divLayer);
 
  // Show the div layer
  divLayer.style.display = 'block';
  // Change the location and reset the width and height if window is resized
  window.onresize = function()
  {
    if (divLayer.style.display == 'block')
    {
      SetTopLeft(divLayer);
      SetHeightWidth(divLayer)
    }
  }
  // Set the dialogbox display message
  document.getElementById('confirmText').innerText = msg;
}

The above function takes 3 parameters. The first is the message you want to display for the user, the second is used to specify the width of the dialog box and finally the third is used to specify the height of the dialog box. If the last two parameters were not supplied, default values will be set.

After setting the height, width, top, and left properties to the div layer, we will make it visible by setting the display to block.

Note the use of window.onresize which will call the SetTopLeft and SetHeightWidth functions if the div layer is visible, which will make the layer re-locate itself.

The final line of code is used to set the div layer (id = confirmText) to the message sent by the developer.

Listing 3

function SetTopLeft(divLayer)
{
  // Get the dialogbox height
  var divHeightPer = divLayer.style.height.split('px')[0];
 
  // Set the top variable
  var top = (parseInt(document.body.offsetHeight) / 2) - (divHeightPer / 2)
  // Get the dialog box width
  var divWidthPix = divLayer.style.width.split('px')[0];
 
  // Get the left variable
  var left = (parseInt(document.body.offsetWidth) / 2) - (parseInt(divWidthPix)
    / 2);
  // set the dialogbox position to abosulute
  divLayer.style.position = 'absolute';
 
  // Set the div top to the height
  divLayer.style.top = top
 
  // Set the div Left to the height
  divLayer.style.left = left;
}

The above function is used to set the location of the dialog box. After some calculation, we get the top and the left where the div layer should be displayed and set them to the top and left property of this dialog box. First we get the div layer height (without the px) and then we divide the window height and width by 2 in order to centralize the dialog box, finally we set the div layer position to absolute.

Listing 4

function SetHeightWidth(divLayer)
{
  // Set the dialogbox width
  divLayer.style.width = divWidth + 'px';
  // Set the dialogbox Height
  divLayer.style.height = divHeight + 'px'
}

The above listing is used to set the height and the width of the dialog box. This function will be called whenever the window is resized and when the DisplayConfirmMessage method is called. Note that the only parameter it takes is the div layer object.

Listing 5

function SetText(txtButton1, txtButton2)
{
  // Set display text for the two buttons
  if (txtButton1 == null)
    document.getElementById('btnConfOK').innerText = txtFirstButton;
  else
    document.getElementById('btnConfOK').innerText = txtButton1;
 
  // Set display text for the two buttons
  if (txtButton2 == null)
    document.getElementById('btnConfCancel').innerText = txtSecondButton;
  else
    document.getElementById('btnConfCancel').innerText = txtButton2;
}

The above listing is used to display the text of the two buttons; this will give you the ability to change and customize their texts concerning your needs. This function takes two string parameters.

Listing 6

function SetDefaultButton(defaultButton)
{
  // Set the focus on the Cancel button
  document.getElementById(defaultButton).focus();
}

The above function is used to set the default selected button when the dialog box is visible; as I already mentioned, the default dialog box will set this button always to the "OK" button. Using this function you can also customize it the way you want. This function takes one string parameter.

Implementation

In this section you will learn how you would implement this dialog box into your project. Navigate to a webform, go to its design mode and paste the HTML code between the <form> tag.

Now create a javascript file called CustomDialog.js in your application root folder, paste all the JavaScript functions and add the following code in the <head> section in the HTML.

Listing 7

<script language="javascript" src="CustomDialog.js"></script>

The above code will link the javascript file you already created to the webform. After this stage, you can add JavaScript code to call the functions on button click, for example.

Listing 8

<script language = JavaScript> 
function ShowMessage()
{
  SetText('Yes', 'No');
 
  DisplayConfirmMessage('are you sure', 180, 90)
 
  SetDefaultButton('btnConfOK');
  return false;
}
</script>

The first thing you need to do is to set the text to be displayed on the buttons (I have chosen Yes and No), the second thing is to display the confirmation message and send the appropriate parameters, the third thing is to set the default button, in this case I chose the Yes button, finally the return false is used to cancel the postback.

Now to call this function on button click, add the following code to the page_load event.

Listing 9

Button1.Attributes.Add("onclick","return ShowMessage()");

Figure 1

The above figure shows the confirmation dialog box when the user clicks on the Button. Note that this is displayed in the maximized window size.

Figure 2

The above figure will show the new location of the dialog box by just resizing the window.

Downloads

Conclusion

After reading this article you will realize how easy it is to create customizable controls upon our needs.

Happy Coding



User Comments

Title: bn m   
Name: v mvb
Date: 12/18/2012 1:55:07 AM
Comment:
v v
Title: gdfgdfg   
Name: gdfgdf
Date: 10/22/2012 7:08:34 AM
Comment:
dfgdf
Title: How to react   
Name: xyz
Date: 9/6/2012 5:40:55 AM
Comment:
Mr.Malak..
u do not find ny yes no buttons in design..
Title: gbfb   
Name: gfg
Date: 9/3/2012 3:24:59 AM
Comment:
gbf
Title: sdf   
Name: asdf
Date: 7/24/2012 1:06:39 AM
Comment:
asdf
Title: aaaaa   
Name: bbbbbbbbbb
Date: 6/14/2012 12:56:42 AM
Comment:
bbbbbbbaaaaaaa
Title: sdfa   
Name: asd
Date: 6/8/2012 1:55:35 AM
Comment:
asd
Title: a   
Name: a
Date: 5/27/2012 4:46:40 PM
Comment:
ssasa
Title: 2012 NFL jerseys   
Name: NIKE NFL jerseys
Date: 5/20/2012 11:29:29 PM
Comment:
[/pre]Cheap NFL,NBA,MLB,NHL
[url=http://www.jersey2shop.com/]Jerseys From China[/url]
[url=http://www.jersey2shop.com/]2012 nike nfl Jerseys[/url]
[url=http://www.jersey2shop.com/]cheap China Jerseys[/url]
[url=http://www.jersey2shop.com/]Sports Jerseys China[/url]
[url=http://www.jersey2shop.com/NFL-Jerseys-c68/]NFL Jerseys China[/url]
[url=http://www.jersey2shop.com/NBA-Jerseys-c77/]NBA Jerseys China[/url]
NHL Jerseys China
[url=http://www.jersey2shop.com/MLB-Jerseys-c94/]MLB Jerseys China[/url]NFL jerseys For Sale online.All Our Jerseys Are Sewn On and Directly From Chinese Jerseys Factory
[/pre]
[pre]We Are Professional China jerseys Wholesaler
[url=http://www.cheapjersey2store.com/]Wholesale cheap jerseys[/url]Cheap mlb jerseys
[url= http://www.cheapjersey2store.com/]2012 mlb all atar jerseys[/url]
[url= http://www.cheapjersey2store.com/ [/url]Cheap China Wholesael[/url]
[url= http://www.cheapjersey2store.com/]Wholesale jerseys From China[/url]
[url=http://www.cheapjersey2store.com/]2012 nike nfl Jerseys[/url]Free Shipping,Cheap Price,7 Days Deliver
[/pre]
[/pre]
We are professional jerseys manufacturer from china,wholesal
sports [url= http://www.cheapjersey2store.com/]Jerseys From China[/url]
[url=http://www.cheapjersey2store.com/NFL-Jerseys-c68]NFL jerseys China[/url]
[url=http://www.cheapjersey2store.com/NHL-Jerseys-c96/]NHL Jerseys China[/url]
[url=http://www.cheapjersey2store.com/NBA-Jerseys-c77/]NBA Jerseys China[/url]
[url=http://www.cheapjersey2store.com/MLB-Jerseys-c94/]MLB Jerseys China[/url]
[url= http://www.cheapjersey2store.com/]China Jerseys[/url],Free Shipping
[/pre]
[/pre]
We are professional jerseys manufacturer from china,wholesal
sports [url= http://www.jerseycaptain.com/]cheap jerseys sale online [/url]
[url= http://www.jerseycaptain.com/]2012 nike nfl Jerseys[/url]
[url=http://www.jerseycaptain.com/NFL-Jerseys-c68]cheap NFL jerseys China[/url]
[url=http://www.jerseycaptain.com/NHL-Jerseys-c96/]NHL Jerseys C
Title: how can i do return true or false   
Name: james
Date: 2/23/2010 12:02:50 AM
Comment:
how can i do if the clicked yes button retrun true and if clicked No button retrun false
Title: Mr   
Name: Sakthi
Date: 2/14/2010 7:08:37 AM
Comment:
Hi this is cool
Title: feed back   
Name: vandan
Date: 1/2/2010 8:22:19 AM
Comment:
THIS IS VERY GOOD SITE.....
Title: Execute code behind based on button clicks   
Name: Archna
Date: 9/22/2009 2:15:25 PM
Comment:
I used the code above, customized the getElementByid and successfully executed and got the confirm box.
In my application there is a gridview and a delete button associated with every row, if the user presses the delete button, this dialog pops up, however unlike the javascript confirm dialog that returns true/ false based on which button was clicked (Ok/ Cancel), this one just postsback the page. Is there a way to resolve this?

Any help appreciated.

Thanks.
Title: Good One   
Name: Rudra
Date: 8/27/2009 7:52:24 AM
Comment:
Nice one. I used it with little customization. on YES?No button we can react with code behind.
Keep us doing good work!
Title: Thanks   
Name: Emily
Date: 6/26/2009 10:36:27 AM
Comment:
Very useful. Wanted to thank.
Title: Good but...   
Name: Khan
Date: 6/18/2009 3:02:51 AM
Comment:
Nice job but It could have been better. The functions SetText(),DisplayConfirmMessage() and SetDefaultButton() all could have been incorporated into one function and the Buttons should have returned a value of yes/no to the calling javascript function then it would be easy to validate and do some stuff based on choice! Also this could be attached to the window.confirm event then it would be simple to call...
Title: Wow   
Name: Great article
Date: 5/5/2009 3:58:44 AM
Comment:
I'll put it to good use!
Title: Amazing   
Name: qwerty
Date: 5/5/2009 3:54:27 AM
Comment:
Wow! What language did you use here?
Title: how?   
Name: how
Date: 4/1/2009 4:16:56 PM
Comment:
why all the coding cant work when combined it all together?can you give me a full one.i need it for urgent,please help me.thanks
Title: the title   
Name: the name
Date: 2/13/2009 7:08:42 PM
Comment:
all good!
Title: just asking   
Name: Rolando
Date: 2/11/2009 9:04:55 PM
Comment:
Hi amm just asking how to make a comment box using ASP.net i mean how to manipulate it???
Title: Thank you   
Name: omar
Date: 11/4/2008 3:08:57 AM
Comment:
Thanks for this
Title: Mr.   
Name: Feroze
Date: 10/3/2007 7:15:09 AM
Comment:
Hello
Title: Control's ID Changed   
Name: Huang
Date: 9/22/2007 12:21:41 AM
Comment:
When running the application,some of the controls' IDs changed, getElementById method runs into error.
Title: Good work   
Name: Joe keer
Date: 9/19/2007 10:58:41 AM
Comment:
Good article.
Title: No problem   
Name: Josh Stodola
Date: 8/30/2007 4:13:20 PM
Comment:
You're welcome. Changing innerText to innerHTML should make this cross-browser. I don't see any other potential problems except for body.offsetWidth and body.offsetHeight. However, even if those properties do not work in other browser's, at least the main purpose of this function will still work fine.

Best regards...
Title: Re: InnerText   
Name: Haissam Abdul Malak
Date: 8/29/2007 5:45:56 PM
Comment:
Josh thank you for providing this useful information.

Shikha i will try to customize the code to run accross different browsers.

Best Regards,
Title: InnerText   
Name: Josh Stodola
Date: 8/29/2007 5:14:26 PM
Comment:
innerText only works in IE. Probably should be using innerHTML instead.

Best regards...
Title: Reg:Custom Message Box   
Name: Shikha
Date: 8/29/2007 11:02:07 AM
Comment:
Ya the control is really good and useful but not working with other browsers, please provide the solution for that also as i need the same for Opera, Netscape, Safari and Mozila browsers.
Title: Re:How to react   
Name: Haissam Abdul Malak
Date: 8/28/2007 4:07:31 PM
Comment:
Download the solution and use the below code to display an alert if the Yes button is clicked for example
btnConfOK.Attributes.Add("onclick","alert('test');");
The above code will call a javascript alert to display a message. And if you want to use the server side event, just double click on the "Yes" button on design mode to handle its click event. Hope it is clear now for you and it isnt "Useless" for you
Title: How to react   
Name: unknown
Date: 8/28/2007 3:24:26 PM
Comment:
This is completely useless, how can you react to which button was pressed?! If they choose yes, I want to do this code-behind. If they choose no, I want to do other code-behind. This dialog does nothing!

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2014 ASPAlliance.com  |  Page Processed at 12/18/2014 9:15:10 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search