Click here to Skip to main content
Click here to Skip to main content

JQuery Message Box Plugin

By , 6 Oct 2011
 
Article.PNG

Introduction

Sometimes, when working with JavaScript, we need to write a confirm dialog or message box to display some informative data. We can either use JavaScript alert function or confirm function for such operations. But in order to make a nice UI, we can resort to JQuery UI dialog, which gives a nice chrome window. But settings that up is not a one liner task. In this article, I will present a small plugin which will help us display some basic dialog just to get the job done without too much code.

Background

JQuery UI library is getting more and more popular for doing web 2.0 style user interface. The library provides a rich set of widgets and the Dialog component is one of them. But to display a dialog, one would need to setup some div and the content of the dialog. You can then call the dialog function display with a lot of optional options for customization.

Using the Code

The plugin is very simple and small, download the code block and make a reference to the scripts right after you have referenced the jquery lib and UI lib. Caution, without the UI lib, the plugin won't work.

(function($)
{
	$.msgBox = $.fn.msgBox = function(msg, onDialogClosed, customOpt, buttons)
	{
		.....
	};

	$.fn.msgBox.defaults =
	{

		height: 200,
		width: 400,
		title: "Message",
		modal: true,
		resizable: true,
		closeOnEscape: true
	};	

	$.fn.msgBox.confirm = function(msg, onConfirm, yesNo)
	{
		.....
	}

	$.fn.extend({ 
         
        //pass the options variable to the function
        confirmLink: function(options) {
			.....           
        }
    });

})(jQuery);

To use the plugin, first make a reference in the head section:

<link type="text/css" href="css/ui-lightness/jquery-ui-1.8.16.custom.css" 
rel="stylesheet" />
<script type="text/javascript" src="js/jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.16.custom.min.js"></script>
<script type="text/javascript" src="js/jquery.msgBox.v1.js"></script>

To display a message box, simply call as follows:

$.msgBox("Hello World");

You can optionally specify the callback handler when the dialog is closed or custom title, etc.

$.msgBox("Hello World Demo with Custom Title", null, { title: "My Title" });

To display a confirmation dialog, use the following:

$.msgBox.confirm("Are you sure?",function(){
		alert("OK Clicked");
});

Now to something more useful, you use the confirmLink method to hook up any links to auto display a confirm dialog. The anchor rel attribute will be used by default to display the dialog text.

$("#confirmDemo2").confirmLink();
....
<a href="http://www.google.com" id="confirmDemo2" 
rel="Are you sure you want to visit google?">
	Click to display a confirm dialog (inline)</a>

For submit buttons, you could use the following:

$(".confirmButton").confirmLink();
....
<input type="submit" value="Submit" class="confirmButton" 
	rel="Are you sure you want to visit google?" />

Behind the Scenes

For those of you who want to understand how the plugin works, here is a little detail. To display the jquery UI dialog, you need a div section to be declared in your page along with the dialog contents. Now every time on every page if we need to do that, it becomes tedious. So what the plugin does is to inject a hidden div at the end of BODY to be used with the dialog. It creates the div the first time the function is called. Next time, it will reuse the div.

if (div.length == 0) {
    div = jQuery("<div id=\"msgBoxHiddenDiv\" title=\"Message\" 
	style=\"font-size: 10pt;display:none\"><p id=\"msgBoxHiddenDivMsg\" 
	style=\"font-size: 10pt; color: black; text-align: center\"></p></div>");
    div.appendTo(document.body);
    var dialogOpt = {
        bgiframe: true,
        autoOpen: false,
        height: opts.height,
        width: opts.width,
        modal: opts.modal,
        resizable: opts.resizable,
        closeOnEscape: opts.closeOnEscape,
        draggable: opts.draggable,
        buttons: $.fn.msgBox.defaultButtons
    };
    div.dialog(dialogOpt);
}

Points of Interest

Make sure you have referenced JQuery UI library. Most of the msgBox functions take optional parameters if you need to customize.

You can probably extend the plugin in many ways, like UI lib detection, etc., and also there are a lot of alternatives out there. I just tried to keep it simple to be handy and useful.

History

  • V1 - Basic Message Box and Confirm Dialog functionality
  • V1.1 - Include support to handle INPUT nodes, and bug fix for Firefox. Included an ASP.NET web app demo in download

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Sazzad Hossain
Binary Quest
Australia Australia
Member
Sazzad is working as a developer since 2001 in the Realestate Market in Melbourne. Likes to work in C# and .Net platform. Started an ISV Business in 2008 called Binary Quest.
 
Follow me on Linked In

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionJquery message box is not support in gridview controlmemberprassin19 Dec '12 - 20:42 
Hi,
 
when i attach the confirmation message code on my gridview delete button its not working when click delete.. when i click the delete button that time the message box was appear next i click the ok button the deleting process is not working. there is no event has occur while click the ok button.. when click ok button the page got refresh. i have applied ajax update panel on my gridview control.. please have help the scenario...
 
Regards,
 
Prassin
GeneralMy vote of 5memberАslam Iqbal14 Oct '12 - 19:59 
Excellent ArticleSmile | :)
GeneralMy vote of 5memberasal_666 Jul '12 - 21:05 
i use it in nested page and its work
i am begginer in asp but ur article realey help me
i hope the god alwayse help u
tnxxxxxxxxxxxxxxxxx
Smile | :)
Questionclass cssmemberBeecoolStrass2 Apr '12 - 23:49 
Hello,
I added : dialogClass:opts.dialogClass, in var dialogOpt
and dialogClass:'dialog-custom' in $.fn.msgBox.defaults
 
so what do you think ? and how I can use it in customOpt ? do you have an example
 
thank you
AnswerRe: class cssmemberSazzad Hossain11 Apr '12 - 18:23 
yes feel free to modify the code as you require.. i think its nice to add the css option. cheers.
-----------------------------
@SazzadHossain

GeneralMy vote of 4memberkaoruji22 Nov '11 - 22:01 
thanks a lot! was looking for a simpler solution
BugSolution in ImageButtonmemberMGM.658621 Oct '11 - 23:33 
Hi, great job! Smile | :)
I found out that when use this for image buttons , confirmation shows but in confirm nothing happen !
 
this is the work out:
 
obj.click(function(event) {
 
                    event.preventDefault();
                    $.msgBox.confirm(msg, function() {
                        if (event.target.tagName == "INPUT") {
                            $(event.target).closest("form").submit();
                        } else if (event.target.tagName == "A") {
                            window.location.href = $(event.target).attr("href");
                        } else if (event.target.tagName == "IMG") {
                            window.location.href = $(event.target.parentNode).attr("href");
                        }
                    });
 
sorry for my bad english
take care
MGH

GeneralRe: Solution in ImageButtonmemberSazzad Hossain22 Oct '11 - 3:07 
thanks for the fix Smile | :) . I will try to include this to the demo soon.
-----------------------------
@SazzadHossain

GeneralMy vote of 5memberMGM.658618 Oct '11 - 21:09 
this is easy and great !
GeneralMy vote of 2memberMunim Abdul6 Oct '11 - 21:15 
If I need to a message box every now and then - I would go for a method on my helper class.
 
Make it more configurable, that will put some extra value in it.
 
Good job by the way.
Regards.
GeneralRe: My vote of 2memberSazzad Hossain6 Oct '11 - 23:47 
not sure if i agree with u.. this is a plugin for jquery, not a mvc topic.. as for more configurable each function takes options, like title etc.. the main point here is to replace alert() with a nicer one.
 
anywho.. for displaying msg on a asp.net mvc projects i would go with customizing baseclass and make use of dynamic viewbags with some type safety to get best of both worlds.. but that's a blog article for another time..
 
cheers mate..
-----------------------------
@SazzadHossain

GeneralRe: My vote of 2memberMunim Abdul7 Oct '11 - 2:29 
Sorry, it's my failure not to mention that I was talking about Javascript not the server side part. Probably you are not used to OOJS.
PS: Use dynamic properties with caution. If I were you, I wouldn't use viewbags on the case you mentioned.
 
Regards mate.
GeneralRe: My vote of 2memberSazzad Hossain7 Oct '11 - 2:49 
Whatever u use on JS side u will end having to call a one liner method anyway, either u short circuit ur objects with prototype or any pseudo OO in js technique. And as for ViewBag, there is a reason the mvc team put it there. It's convenience over control.
 
The article is marked for beginners who wants a quick dirty way of replacing alert() with $.msgBox(), which perhaps is too simple for ur liking. Btw no point guessing what others are "used to", I grew up programming on a box with a z80 cpu.
-----------------------------
@SazzadHossain

GeneralRe: My vote of 2memberMunim Abdul7 Oct '11 - 4:13 
Sorry for this argument raised. I am not a blogger/writer but what I understand is, "quick and dirty way" are normally blogs and articles are more precise on its subject. You probably know about it better than me.
 
Anyway, I just requested you to provide some features to your plugin like old style VB "MsgBox", which would give you some value to your article.
 
PS: Probably this is not the right place to tell people how you grew up.
GeneralMy vote of 3memberMember 21280846 Oct '11 - 15:45 
good,,
GeneralMy vote of 5memberMd. Rashim uddin6 Oct '11 - 9:13 
It's nice to continue the contribution in that such of platform which help me much and others as well. Could we expect to see you with an another nice article specially on routine engine.
 
All in All this is a good Job. Carry on Pls.
 
Cheers,
Rashim
Questionhow could this confirm cause post back?memberLongxe4 Oct '11 - 23:46 
how could I make the yes button(on confirm box) on click cause a post back and raise the delete button onclick on server.
AnswerRe: how could this confirm cause post back?memberSazzad Hossain5 Oct '11 - 0:03 
Here is the code snippet for doing a postback if the user confirms the dialog.. assuming u have a page called Default.aspx like this:
 
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ConfirmDemo._Default" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Test Confirm Dialog</title>
    <link type="text/css" href="css/ui-lightness/jquery-ui-1.8.16.custom.css" rel="stylesheet" />
    <script type="text/javascript" src="js/jquery-1.6.2.min.js"></script>
    <script type="text/javascript" src="js/jquery-ui-1.8.16.custom.min.js"></script>
    <script type="text/javascript" src="js/jquery.msgBox.v1.js"></script>
    <script type="text/javascript">
        $(function() {
            $("#LinkButton1").confirmLink();
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:LinkButton ID="LinkButton1" runat="server" onclick="LinkButton1_Click" rel="Are you sure?" >Try Deleting Me</asp:LinkButton><br />
        <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
    </div>
    </form>
</body>
</html>
 
And the code behind looks like this:
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
namespace ConfirmDemo
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
 
        }
 
        protected void LinkButton1_Click(object sender, EventArgs e)
        {
            Label1.Text = "User Clicked OK";
        }
    }
}
 
I will email u the sample solution to ur private inbox. Cheers.
-----------------------------
@SazzadHossain

GeneralRe: how could this confirm cause post back?memberLongxe5 Oct '11 - 16:40 
how about the onclick on a submit button(<input type="submit"/>)?
GeneralRe: how could this confirm cause post back?memberSazzad Hossain5 Oct '11 - 21:31 
i have updated the plugin to include support for that. Uploaded the new code here and will be updated shortly as soon as the CP Editor approves it. Cheers.
-----------------------------
@SazzadHossain

QuestionI don't get why you are wrapping a existing JQuery extension that is already fine to usemvpSacha Barber4 Oct '11 - 4:24 
I don't get why you are wrapping a existing JQuery extension that is already fine to use. What is the point of this extra layer or abstraction. The JQuery.UI Dialog jQuery extebsion already works just fine. Why complicate it any further.
 
[Edit]
Actually I guess if you are trying to get your code to be precise, one line is better than several, so I guess I get it now. I would have typically just had a function that did this, so I suppose this is no different. Ignore my previous comments. I now get it
Sacha Barber
  • Microsoft Visual C# MVP 2008-2011
  • Codeproject MVP 2008-2011
Open Source Projects
Cinch SL/WPF MVVM

Your best friend is you.
I'm my best friend too. We share the same views, and hardly ever argue
 
My Blog : sachabarber.net

GeneralMy vote of 3memberPetr Pechovic4 Oct '11 - 4:23 
Well, you used a lot of work from others and added just a few lines of yours. Would be nice to mention original source. Also from article we expect a bit detailed description and thoughts.
 
Cheers,
Petr.
GeneralRe: My vote of 3memberSazzad Hossain4 Oct '11 - 5:10 
The first time I wrote this plugin was back in early 2010. Obviously for the dialog I have used JQuery UI library, which I think everyone knows what it is. As for the rest of it, these are just plain "plugin writing guide" and basic jquery stuff. Head over to jQuery website you will find snippets under their plugin writing guide. As for finding similarity with other plugins well there is probably hundreds of them out there.
Cheers..
-----------------------------
@SazzadHossain
-----------------------------

GeneralMy vote of 4memberkiran dangar4 Oct '11 - 3:25 
Expecting more explanation on Plug-In
GeneralRe: My vote of 4memberSazzad Hossain4 Oct '11 - 4:03 
Thanks for you feedback and I agree with you, should have explained a bit more regarding how the plugin is working behind the scene. I will try to edit the document to include some more text soon.
 
Thx
-----------------------------
@SazzadHossain
-----------------------------

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130523.1 | Last Updated 6 Oct 2011
Article Copyright 2011 by Sazzad Hossain
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid