jQuery Alert Dialogs (Alert, Confirm, & Prompt Replacements)

A set of methods that provide an inline, customizable way to show JavaScript alerts, confirmations, and prompts.

Contents

  1. Overview
  2. Usage
  3. Compatibility
  4. Demo
  5. Download
  6. Known Issues
  7. Licensing

Overview

This jQuery plugin aims to replace the basic functionality provided by the standard JavaScript alert(), confirm(), and prompt() functions. What’s the benefit of using custom methods? Well, a few good reasons, really:

These methods simulate a true modal dialog box. They will automatically re-position themselves if you resize the browser window (unlike many existing dialog/lightbox-style plugins). If you include the jQuery UI Draggable plugin, the dialogs can be moved by dragging their title bars. Everything you need to produce the dialogs in the demonstration is included in the download.

Requires jQuery 1.2.6 or above.

Implementation

Include the following in the <head> section of your HTML document(s):

<!-- Dependencies -->
<script src="/path/to/jquery.js" type="text/javascript"></script>
<script src="/path/to/jquery.ui.draggable.js" type="text/javascript"></script>
<!-- Core files -->
<script src="/path/to/jquery.alerts.js" type="text/javascript"></script>
<link href="/path/to/jquery.alerts.css" rel="stylesheet" type="text/css" media="screen" />

Make sure you update the path to the respective files. If you are already using the jQuery UI Draggable plugin (including the UI core), simply omit the link to jquery.ui.draggable.js.

Usage

This plugin utilizes the $.alerts namespace, but there are three built-in shortcut functions that make implementation easier:

Unlike their native JavaScript counterparts, you can use HTML in the message parameter. To specify a newline, you can use either \n or <br />.

These methods do not return the same values as confirm() and prompt(). You must access the resulting values using a callback function. (See the demo for more details.)

Compatibility

This plugin requires jQuery 1.2.6 or above and has been tested to work in the following browsers:

Demo

Visit the live demonstration page to see examples of each dialog.

Download

Download the current version of this plugin: Version 1.1

This plugin is provided to you as-is, at absolutely no cost. If you would like to support its development, feel free to contribute any amount you prefer via PayPal. As always, you are welcome to contribute code for bug fixes and feature enhancements as well. Either way, thanks for supporting our efforts!

Known Issues

Licensing

This plugin is dual-licensed under the GNU General Public License and the MIT License and is copyright 2008 A Beautiful Site, LLC.

Comments

Very nice. I'd like to use it, but the GPL license is too restrictive.

xcdesz on Dec 30th, 2008

Thank you very much, pretty useful to me !
I added a popup method : jPopUp

If you're interested contact me ;)

Paul on Dec 30th, 2008

It would be nice to have an option to keep stuff out of the global namespace.

Otherwise very nice :)

Richard Garbutt on Dec 30th, 2008

Regarding namespacing, the problem I have is with the shortcut functions (jAlert, etc.) being defined in the global namespace and there being no way to prevent this. I don't think library code should do this and I probably wouldn't use the plugin because of this issue.

Richard Garbutt on Dec 30th, 2008

@Richard: That's a fair argument. Of course, the shortcut functions could easily be removed. I actually debated putting them in there in the first place, but they seem to make it easier for novice users than something like $.alerts.alert().

Perhaps I'll offer the shortcut functions as "copy and paste code" in the future - or simply deprecate them altogether.

Thanks for your feedback :)

Cory S.N. LaViska on Dec 30th, 2008

This looks good, like the CSS styling option.
But what I expected when I followed a link here was - at last! - to be able to specify the number of buttons and their text...
Now that would really make me use this :)

Tian on Dec 31st, 2008

@Tian: you can change the text of the buttons:

$.alerts.okButton = 'Sure';
$.alerts.cancelButton = 'No Way';

There are some other properties that you can change, as well. See the source code for details.

Cory S.N. LaViska on Dec 31st, 2008

Im sorry im new to jquery.. id like to know how to set this up onload?

thanks

ingenium on Dec 31st, 2008

First of all, Happy New Year to all... :)

@ingenium:

If you want to set after loading the page, then try this:

$(document).ready(function () {
jAlert('loaded!');
});

This means same,
window.onload = function() { alert('loaded'); };

i.e. an alert message will pop-uped, after loading the page.

Suhas Dhoke on Jan 1st, 2009

How would one change the position of the alert? Is this possible without hacking the code? In Opera 9.63 it appears a bit low.

Cheers

Josh on Jan 1st, 2009

@Josh: To adjust the position, set $.alerts.verticalOffset and/or $.alerts.horizontalOffset to an integer value (in pixels) before calling an alert. The default is -75 and 0, respectively.

Cory S.N. LaViska on Jan 1st, 2009

Thanks, that's great. And what a great script, too! (And also, your CMS - very original way of doing things. I like it!)

Josh on Jan 1st, 2009

Hi, nice job, can you just explain me, how to work with callback function in jConfirm - I just want to return true or false from this confirmation, just like in confirm(). Thanx.

Tom on Jan 3rd, 2009

@Tom: in the second example on the demo page, the parameter 'r' is the true/false value that the user selects from the confirmation dialog.

Cory S.N. LaViska on Jan 3rd, 2009

Hi, yes, I know about the "r". I just dont know how to return this value from this whole dialog. I have simple form with onsubmit=jConfirm (or onsubmit=return jconfirm?), can you please tell me how can I return the true/false into thit form? Thanks a lot.

Tom on Jan 3rd, 2009

@Tom: instead of

onsubmit="if( jConfirm(...) ) doSomething()";

(which won't work), do this:

onsubmit="handleSubmit()";

And create the 'handleSubmit' function that has the jConfirm() in it, then use the example to guide you from there.

Tip: you'll get bonus points for coding it unobtrusively instead of inline :P

Cory S.N. LaViska on Jan 3rd, 2009

Hi,yes I´ve tried to do that, unfortunetaly I`m a "lightweight" Javascript user :( Maybe some beginners examples in your demo would help.. I just don´t know how to get the answer from this confirm, f.e. into some variable or something.

Tom on Jan 3rd, 2009

I've been looking for a script like this for a while and today I gave up and started making it myself but then I found this script. Thanks :D

PS. In /includes/validation.js on line 56, change the {2,3} to {2,4}. Don't forget the .name people like me.

Elijah Grey on Jan 4th, 2009

Actually, just change it to check the TLD for validity and not length.

Elijah Grey on Jan 4th, 2009

Hello Friends,

Is there any way to fix the problem "ENTER and ESC keys (to accept/cancel) don’t work in WebKit browsers" ????

Thanks in advance.

Sachin on Jan 5th, 2009

in a iFrame ,it not work!

var on Jan 7th, 2009

I'm having problems with the jConfirm (similar to Tom). How do you get the results outside of the handleSubmit() function you suggested? I'm trying to do the following, but var selection doesn't get updated in time. How can I wait for the javascript callback? A Google search didn't help me find that answer.
function confirmAction()
{
var selection = false;
jConfirm('Continue?', 'Confirmation Dialog',
function(r) {
selection = r;
alert(r);
});
if (selection) {
DisableButton();
// do the action
return true;
}
else {
//user clicked cancel, don't execute the action
return false;
}
}
Then in my asp button:
<asp:Button ID="btnUpload" runat="server" Text="Import Data" EnableViewState="false"
OnClick="btnUpload_Click" OnClientClick="return confirmAction();" />

Thanks.

Kevin on Jan 12th, 2009

@Keven:

0 vote down


Hi there,

I think I have come up with a possible solution to this problem. I was reading this article: http://treasure4developer.wordpress.com/2008/06/23/calling-postback-event-from-javascript/

Basically the idea is that you force the postback from javascript, at first I found that the postback would work but wouldn't call my button event, but after reading the article I found that I could detect if it was javascript postback and just call a method to do the processing

Regards DotnetShadow

DotnetShadow on Jan 14th, 2009

Having some trouble with using this onload... When I use the code posted from someone up above:
$(document).ready(function () {

jAlert('loaded!');

});

In internet explorer, the alert window is below everything else on the webpage. You have to scroll all the way down to see it. In Firefox, it works perfectly. Any ideas?

Spencer on Jan 14th, 2009

@Spencer: nope...can you post an example link?

Cory S.N. LaViska on Jan 14th, 2009

Threw the relevant code into here:

http://streamlinesamples.com/spencer/test/test.html

In IE7 it's screwed up. In IE6 or Firefox it's perfect.

Spencer on Jan 14th, 2009

I have the same problem of Spencer in IE7 and not work in iFrame.

Thiago on Jan 16th, 2009

To fix this problem Spencer change this line
"var pos = ($.browser.msie && parseInt($.browser.version) <= 6 ) ? 'absolute' : 'fixed';" put <=7 to IE 7 and have fun...

Thiago on Jan 16th, 2009

These functions are great, but I'd like to ideally be able to use jconfirm like I do confirm - to test its return value of true or value, and then proceed. If this isn't possible, could someone please explain how the callback is used? I didn't find any documentation for it. Thanks

david on Jan 18th, 2009

Nevermind, I got it to work. Thanks very much for this great control. The following clicks btnok if user clicks ok, btncancel if user clicks cancel (if btncancel is specified):

function MsgOkCancel_jquery(strmsg,btnok,btncancel)
{
$.alerts.confirm(strmsg,'Confirm',
function(r) {
if (r == true) {
if (btnok != null && btnok != "")
document.getElementById(btnok).click();
}
else {
if (btncancel != null && btncancel != "")
document.getElementById(btncancel).click(); }
}
)
}

david on Jan 19th, 2009

Two problems I've run into so far in using with AJAX, vb.net: 1) the images don't appear in alert or confirm. I have referenced the files exactly as in other lines in css files that show the images. This isn't a critical problem; 2) Using jconfirm per the example in #30 above, if I then call jalert from btnok or btncancel, the program fails with the error message that it cannot redirect to the page that is being displayed (the reference is correct, and it's odd why it cannot find that page). I just call jalert in Ajax with SetTimeout - otherwise nothing appears (and I don't get this error message after confirm).

David on Jan 19th, 2009

OK, solved problem #2. I had defined the hidden lnkOK and lnkCancel as postback triggers in the triggers section. Removing these and allow the defaults of AsynchPostbackTriggers cleared that problem. I suspect the missing images can be fixed somehow, easily.

David on Jan 19th, 2009

I really like the idea of this project and it is well written, but jConfirm needs to be easier to use. I tried David's suggestion #30 and had to create a hidden button (using display:none;) for the ok action. The postback after an "ok" works, but then the action gets overridden by the the jQuery javascript.

Also it would be really cool to just call window.confirm = window.jConfirm; or
window.alert = window.jAlert; and override all alerts or confirms already on a site. The idea is from a competing jQuery alert project at http://www.jondavis.net/codeprojects/jqalert/.

Kevin on Jan 21st, 2009

This works pretty well and I have it implemented but I am having a problem with the popup location. Vertically it is always centered with the scroll, but I have a wide page, and if the user scrolls right too far the modal appears way back to the left, more or less off the screen. Is there some way to work around this?

Thanks,
matt

Matt on Jan 22nd, 2009

OK, regarding the above message, I found the problem exists in IE6 but not FF. The workaround is to adjust horizontal offset to the left scroll for me, but maybe there is another solution.

Matt on Jan 22nd, 2009

This doesn't work with scriptaculous. Oops.

John on Jan 22nd, 2009

Can we have Yes, No buttons instead of Ok Cancle on jConfirm?

Sandeep on Jan 23rd, 2009

Does anyone have a sample ASPx page with this implemented (C# or VB) that they can share? I'm very new to this and can't seem to get it working.

BScottA on Jan 23rd, 2009

@Sandeep: please see comment #7

Cory LaViska on Jan 23rd, 2009

Thanks

Jean on Jan 23rd, 2009

Hi,

Great plugin so thanks for that.

I'm having problems similar to Tom (#17) & Kevin (#22).

I need to return the true/false from the jConfirm in the same manner as with a regular confirm ie. so that the handleSubmit() doesn't return a value until the callback value is determined.

I am using an Ajax framework that embeds further javascript into the onclick inline after my code so I need to ensure that I return false immediately if the jConfirm returns false to prevent this Ajax code from being called.

Hope this is reasonably clear. Thanks!

Damian.

Damian on Jan 26th, 2009

Hey everyone. To respond to a number of requests about jConfirm() and jPrompt() returning boolean values like confirm() and prompt():

I don't believe this is actually possible. If it is, it's beyond my knowledge of JavaScript and web browsers in general. As I understand, the alert(), confirm(), and prompt() dialogs that come out of the box are actually handled by the browser itself, and execution of JavaScript actually halts while these alerts are present on the screen. This type of action is not (as far as I know) possible with non-native JavaScript code.

The functions in this plugin simulate their original counterparts as closely as possible within the limited scope of what is possible with JavaScript. If you want to use jConfirm() or jPrompt(), you'll have to use the callback function to obtain the user's response.

Two very clear examples of how to do this are shown in the demo page (linked above), so please use those code samples as a reference. It really doesn't get much simpler than that.

If you're not familiar with callback functions--well, you're using jQuery--that's a fundamental part of this wonderful library :) Still, the examples should be enough to get you started.

Cory S.N. LaViska on Jan 26th, 2009

in IE6 a select element will cover the dialogue. any fix for this?

kyrael on Jan 28th, 2009

on ASP.NET page, dropdownlist controls can still be accessed but other controls cannot be accessed (which is a good thing) which should not be the case when the JQuery Alert dialog is on the page.

Is not this JQuery alert dialog box supposed to be modal on all ASP.NET controls or is there some issue with dropdownlist controls ?? correct me on this please..

jkojs on Jan 28th, 2009

Very nice plugin. The problem is that I use prototype. Any way to use them together on the same page?

Sergei on Jan 29th, 2009

Hi Cory,

Thank you very much for making this plug-in. It works perfectly for me and is exactly what I needed.

I sent donation in appreciation for your work.

- Nibbi

Nibbi on Jan 30th, 2009

Hi everyone!, i have the same problem like all. In IE7, don't work jAlert, in post#27 thiago gives a solution but i don't understand where a have to change this line, in jquery.js? or jquery.alerts.js?. I tried to change in jquery.js but is really confused.
Thanks!!, and sorry for my english but i speak spanish!!!
bye!

Rose on Feb 2nd, 2009

Hi everyone!!!.. i fix the problem, i was so easy!! in jquery.alerts.js, there is a line like this:
"var pos = ($.browser.msie && parseInt($.browser.version) <= 6 ) ? 'absolute' : 'fixed';"
and i have to change 6 for 7 :

"var pos = ($.browser.msie && parseInt($.browser.version) <= 7 ) ? 'absolute' : 'fixed';"

and.. that was all!!!.. well, i have to give my appreciation for this !!..

thanks!

Rose on Feb 2nd, 2009

Please!! i need help! I have the same problem that post#43, in IE6 a select element cover the dialogue, Do you have any solution for this??????
Thanks!.
Rose

Rose on Feb 3rd, 2009

Again, i find a solution for the problem in IE6, when the select elements cover the jAlert.
in jquery.alerts.js you have to put this functions:

function hideSelectBoxes() {
var x = document.getElementsByTagName("SELECT");

for (i=0;x && i < x.length; i++) {
x[i].style.visibility = "hidden";
}
}

function displaySelectBoxes() {
var x = document.getElementsByTagName("SELECT");

for (i=0;x && i < x.length; i++){
x[i].style.visibility = "visible";
}
}

.. with the function hideSelectBoxes() you can hide the select. You may call this function here:

alert: function(message, title, callback, url) {
hideSelectBoxes(); ===>>>HERE!!
if( title == null ) title = 'Alert';
$.alerts._show(title, message, null, 'alert', function(result) {
if( callback ) callback(result);
if(url) self.location.href = url;
});
},

and the function displaySelectBoxes(), show again the select that it was hidden. You may call this function here:

switch( type ) {
case 'alert':
$("#popup_message").after('<div id="popup_panel"><input type="button" value="' + $.alerts.okButton + '" id="popup_ok" /></div>');
$("#popup_ok").click( function() {
$.alerts._hide();
displaySelectBoxes(); ==>>HERE!
callback(true);
});
$("#popup_ok").focus().keypress( function(e) {
if( e.keyCode == 13 || e.keyCode == 27 ) $("#popup_ok").trigger('click');
});
break;

Well.. i hope this code could help you.
Rose.

Rose on Feb 3rd, 2009

Hello,

I've a problem with the jAlert

I'm trying to launch the jAlert from the code behind (c# - ASP.NET)

here is the code I use for it

ScriptManager.RegisterStartupScript(p, p.GetType(), "dummy", "jAlert('" + cleanMessage + "');", true);

when I click on a button, I execute this and I get well the jAlert box but I get also the famous ie operation aborted

anyone having the same problem?

nb : I don't have the problem using jAlert in a "standard way"

GillouX on Feb 5th, 2009

Hi. I use this code:
$("#alert_button").click( function() {
$.alerts.overlayOpacity=0.3;
$.alerts.overlayColor="#00FF00";
jAlert('This is a custom alert box', 'Alert Dialog');
});
When i run it in IE 6.0, overlay is not 100%.

DiemVuong on Feb 6th, 2009

thank you nice jquery work !

العاب on Feb 8th, 2009

Nice plugin, but, is that a way to show the confirm box when you click on link instead input button?

George on Feb 9th, 2009

how to set the TIMEOUT for the JAlert box ??

Any help appreciated..

jkojs on Feb 9th, 2009

In my app I expect to use different alert popups with different icons (and maybe colors), like "Ok"/"Ko"/"Info". How can I set up this?

Lorenzo on Feb 10th, 2009

Hello

Anyone..

Please help me on how to set the TIMEOUT for the JAlert dialog box.

jkojs on Feb 11th, 2009

I have essentially the same question as Tom & Kevin (Jan 3 and 12). I also am a lightweight in this. I know the page says "You must access the resulting values using a callback function," but I don't know what that looks like. It seems like all the explanations assume something that I'm missing. Here's what I'm trying to do: When a user clicks a link, I want to present this jQuery plug-in alert to inform the user he or she is about to leave the site: OK or Cancel. That part works. However, I simply have not been able to retrieve the response into a conditional statement that either issues "event.preventDefault()" if Cancel was selected, or allows the user to go to the link if OK was selected.

smgolden on Feb 12th, 2009

Hmm...let me try to clear this up a bit if I can. Traditional use of, for example, confirm() looks like this:

executeBefore();
if( confirm('Continue?') ) {
// Continue / true
} else {
// Don't continue / false
}
executeAfter();

In this example, executeBefore() will run, then the confirm, and once a user selects OK or CANCEL, executeAfter() will run. To clarify, the execution of your script halts at the native JavaScript confirm (and alert(), and prompt()).

Unfortunately, this native behavior cannot be duplicated. So, if you tried doing this:

executeBefore();
jConfirm('Continue?', 'Confirm', function(r) {
// Do something with 'r'
});
executeAfter();

The executeBefore() function will run, then jConfirm(), and then immediately afterwards executeAfter() will run. The difference being that JavaScript does not halt for jConfirm(), therefore executeAfter() will run while the dialog is still showing (before the user even has a chance to make a selection).

You can easily work with this, however, and if you've spent at least an hour with jQuery you should be more than familiar with basic callback functions:

jConfirm('Can you confirm this?', 'Confirmation Dialog', function(r) {
jAlert('Confirmed: ' + r, 'Confirmation Results');
});

In this example, an alert will show with the true/false value of the jConfirm() function. (Note that 'r' is *only* accessible in the scope of the callback).

If you've ever used $.get() or $.post() than you know that AJAX calls (which essentially work in the background) are handled the same way:

1. User does something to trigger the call
2. $.get() / $.post() method is fired
3. JavaScript keeps on trucking
4. After sometime, the AJAX response is received
5. The callback function is fired

jConfirm() and jPrompt() work exactly the same way, except instead of waiting for the server to respond you're waiting on the user to respond.

Hope this helps.

Cory S.N. LaViska on Feb 12th, 2009

tab Accepted !! and switch on behind of popup. this is a bug that not fixed.

hessam on Feb 13th, 2009

I'm using jalert for all my popup messaging - much nice than alert. One plus would be having an option also to use it non-modally - with the option for no OK button - have a handle available to make it disappear, or have it just disappear on next postback, with all controls on the page assessible. I can do this using an ajax modal popup, but it would be nice to have that option with jalert also. - David

David on Feb 13th, 2009

Re#58 and 59. Thank you very much for your prompt reply. I seem to understand everything you've described. I have even gotten the jAlert to work to display in the secondary message whether true or false were set. That's all the part I've understood. I even understand the purpose of a callback. (BTW: I've spent more than several hours using jQuery and have gotten many nice features to work without running into callback until now. :) ) However, you haven't explained how I make use of the information retrieved in a conditional statement such that when a user selects OK, he or she is taken to the link and if the user selects Cancel, he or she is left on the current page (using "event.preventDefault()", I believe)

Is this an example of a callback?
jConfirm('Can you confirm this?', 'Confirmation Dialog', function(r) {
jAlert('Confirmed: ' + r, 'Confirmation Results');
});
If so, how do I put my conditional statement inside of it?
If not, how would I set up the conditional statement to make use of the value held in 'r'?

smgolden on Feb 13th, 2009

@smgolden: see if this helps. This code will intercept any hyperlink on the page and confirm that the user wants to leave the page before exiting:

$("A").click( function() {
var url = $(this).attr('href');

jConfirm('Leave this page?', 'Confirm', function(r) {
if( r ) {
location.href = url;
} else {
jAlert('User cancelled!');
}
});

return false;
});

I think that's what you were asking.

Cory S.N. LaViska on Feb 14th, 2009

Thank you sooooo much! That's exactly what I wanted. It's working great now.

I have two questions.

1. This is what I had set up. Why didn't it work?
$("a").click(function(){
jConfirm('Can you confirm this?', 'Confirmation Dialog', function(r){
if (r == false) {
(event.preventDefault());
}
});
});

2. What part of the code you provided is the callback? The "function(r)" in the jConfirm statement? Can you describe what it is "calling back" in order to make the process wait for the response?

smgolden on Feb 14th, 2009

@smgolden: the callback is the anonymous function that gets executed when a user makes their selection. Your example didn't work because when they clicked the link it took them to another page. You have to 'return false' to intercept the link.

Remember, everything inside of the callback function won't be executed until *after* the user makes a selection.

Cory S.N. LaViska on Feb 14th, 2009

I hate to seem dense, but "anonymous function?" What part is the anonymous function in:

$("A").click( function() {
var url = $(this).attr('href');

jConfirm('Leave this page?', 'Confirm', function(r) {
if( r ) {
location.href = url;
} else {
jAlert('User cancelled!');
}
});

return false;
});

What part is the callback?

Is it such that the "outer" block that starts with:
$("A").click( function() {
returns "false" immediately and calls the jConfirm function which is then processed?

Did you mean to say "nothing inside of the callback function will be executed until *after* the user makes a selection"?

So, the user clicks a link, $("A") function begins, URL is stored in a variable, jConfirm is initiated, $("A") function returns false, jConfirm executes and presents dialog to user, user makes a choice which is processed by the conditional statement.

Is that the sequence?

If so, if I had put a "return false;" before the last "});" in my code would it have worked?

smgolden on Feb 14th, 2009

Pretty nice jquery plugin!

I'm trying to use it in my asp.net project but I can't figure it out.

I have a asp.net LinkButton control where I do this:
MyButton.OnClientClick = "return JQueryAlert();";

My jquery code looks like this:
function JQueryAlert() {
$(document).ready(function() {
return jConfirm('Can you confirm this?', 'Confirmation Dialog');
});
}

It looks like the asp.net Postback is still happening.

If I replace the jquery code with normal code like:
retun Confirm("can you confirm?");

It works...

Could somebody explain me how I can fix this please? That would be great! Thank you!

Wouke on Feb 17th, 2009

Hi and thanks for the plugin!

I'm having some dificulties with latin special chars.
Even though I declare an utf-8 charset both in my html and css I cannot get the title of the alert to render the special chars (no problem with the message part).

Any ideas?

Thanks in advance!

carolbac on Feb 17th, 2009

I have an error with the alert.

The following comes in firebug...

$("#popup_container").outerWidth is not a function
[Break on this error] minWidth: $("#popup_container").outerWidth(),

niju on Feb 18th, 2009

Hi again.

Nevermind message #68.
I was stupid enough to declare an utf-8 charset in my css page but still save it in ascii... :)
Everything's perfect now.

Thanks again for the plugin!

carolbac on Feb 20th, 2009

Very nice!

redscreen on Feb 24th, 2009

Didn't try it yet, but it seems to be very useful.

cheers!!

hellward on Feb 28th, 2009

Hi, great work!
I'd like to use it if I could tweak jAlert to prompt for multi-line user interaction.
I don't know where to start from... any clue?
Regards

ashorlivs on Mar 4th, 2009

FOUND IT!
For those interested remplace the <input type="text"> line 131 by a <textarea> : )

ashorlivs on Mar 4th, 2009

Also, I had the need to let people write empty value in the prompt (and update my database accordingly). The way jPrompt is done forces the user to type in a value otherwise the callback returns a null value.
In short, I was only able to check if there is a value or not, but I need to check if there is a value or an empty value or no value at all.

I have added a second value to the callback. Param 1 (statut): has the pop-up been validated? and Param2 (result): what was the entered value?

So here is my modified prompt: methode (goes to line 56) :
prompt: function(message, value, title, callback) {
if( title == null ) title = 'Prompt';
$.alerts._show(title, message, value, 'prompt', function(statut, result) {
if( callback ) callback(statut, result);
});
},

It also requires a minor edit in the Switch from line 133 to 141:
$("#popup_ok").click( function() {
var val = $("#popup_prompt").val();
$.alerts._hide();
if( callback ) callback( 1, val );
});
$("#popup_cancel").click( function() {
$.alerts._hide();
if( callback ) callback( 0, null );
});

Now in your calls you can double check the user-entered value:
jPrompt('Text', id, 'Descr', function(s, r) {
if (s) {
if (r) {
alert('u have entered ' + r);
} else {
alert('u have entered a blank value !')
}
} else {
alert('u have cancelled...')
}
}

Cheers,
germain

ashorlivs on Mar 4th, 2009

Any other solution on dialog covered by select controls/element?

Steven on Mar 6th, 2009

Seriously, why not put up some simple examples for people to learn from. All I want is for the custom confirmation placed on a link. OK the user moves forward, CANCEL they go no where. I need the custom styling and to add a link to the popup which is why standard confirm will not work. I've spend hours here with no luck. Please post simple examples, without them most beginners will pass this right up. I have no clue about all the custom programming talk here...

Eric on Mar 8th, 2009

It doesn't get much simpler than what's on the demo page (http://abeautifulsite.net/notebook_files/87/demo/). You have code samples, you can view source, and you have a working demo.

If this is too complicated, then I'd suggest taking the time to learn some fundamental JavaScript and jQuery concepts before using the plugin.

Cory S.N. LaViska on Mar 8th, 2009

This script looks great thank you, but is there anyway to grey out the background so there's more focus on the alert box? Like a transparent overlay?

Thanks

Nick on Mar 10th, 2009

@Nick - use $.alerts.overlayOpacity = .50 to set the overlay. There are more properties that you can modify if you check out the code :)

Cory S.N. LaViska on Mar 10th, 2009

You're an absolute star, will start using this asap, thanks Cory :D

Nick on Mar 10th, 2009

Hi,

Thank you for the plugin.

I had problems with it in FF 3.0.7, Opera 9.64
Debugging and making everything work right took quite a bit of time, hope you will find my update useful.

Please grab it at http://javascript.ru/js/jquery.alerts.js

Ilya Kantor on Mar 11th, 2009

ASP.NET users ... here's the solution to your problem. I finally arrived at this after some effort:

Situation:

You want to bind jConfirm to a Submit button, however while the confirmation dialog does appear it always posts back.

Solution:

// Confirm form save

btnSave.Attributes.Add("OnClick", "if ( !jConfirm( 'Are you sure you want to do this?', 'Save?', function( rt ) { if ( rt ) { " + this.Page.ClientScript.GetPostBackEventReference(btnSave, String.Empty) + " } else { return false; } } ) ) return false;");

Keith on Mar 11th, 2009

Hi,

Thank you for you plugin.

I'm using jquery ui 1.7 and jPrompt, firefox 3.0.7
I open a jquery dialog and after I open a jPrompt window. All is ok except the focus of the prompt input. I can't enter anything, the focus on the input is here, but all key down events (except "enter" and "esc") are not taken.

Thanks for your help :)

Arnaud on Mar 11th, 2009

this will be very usefull. thank you.

anushka on Mar 12th, 2009

Can anyone help me this plugin is not working with mozilla but it is working fine with google chrome...Is there any patch for mozilla

krishnan on Mar 13th, 2009

How do you get multiple pop-up links on a single page? I wanted to include the function site-wide but now I realize each link needs to call a unique ID and that ID needs to be separate in the function above.

Any work arounds? I have pages with dozens of links that need this popup and they are dynamically generated. How can I simplify? I really hope there is a way, I spent hours getting this to work and then realized two on the same page doesn't work!

Eric on Mar 13th, 2009

This is great but how in the world do you get something to happen after it fires? I was trying to set focus on a field after the alert using:

jAlert("Some Message.");
$('#somefield').focus();

but nothing happens. Really frustrating!

Matt on Mar 23rd, 2009

Matt, I did something along these lines if it's helpful to you:

<script type="text/javascript">
$(document).ready( function() {
$("#MP1,#MP2,#MP3").click( function() {
var url = $(this).attr('href');
jConfirm('Dialog body copy here', 'User Agreement', function(r) {
if( r ) {
location.href = url;
} else { } });
return false; }); });
</script>

<a href="http://www.cnn.com"; id="MP1">Link 1</a><p>
<a href="http://www.cnn.com"; id="MP2">Link 2</a><p>
<a href="http://www.cnn.com"; id="MP3">Link 3</a><p>

Eric on Mar 23rd, 2009

Thanks Eric! That was really helpful in understanding how this works.

Matt on Mar 24th, 2009

How would I make a link open in a new window?

$(document).ready( function() {
$("a.external").click( function() {
var url = $(this).attr('href');

jConfirm('Please note you are now leaving our website to a new domain.', 'Confirm', function(r) {
if( r ) {
location.href = url;}

});

return false;
});
});


I tried this:
location.href = window.open(url);}

But it placed [objectWindow] in my current window.
http://www.mysite.com/[objectWindow]

However it did open link in new window.

Sorry for the noob question in advanced.

Steve on Mar 24th, 2009

muy bueno

Juan Machado on Mar 24th, 2009

Cool stuff!

A shame that the dialog appears at the very top of a long page in MSIE7 though.

Could I do something to have the dialog appear in the middle of the current viewport (as firefox does)?

dth on Mar 25th, 2009

@dth: could you provide a test case so I can troubleshoot the issue you're experiencing? Thanks :)

Cory S.N. LaViska on Mar 25th, 2009

Great job! This is very nice and useful. One simple question, though: How can I use more than one jAlert on a page?

For example, let's say I'm running a client-side form validation script like this:

function Validate()
{
if ( document.register.name.value == "" )
{
jAlert('Please supply your name.', 'Alert Dialog');
valid = false;
}

if ( document.register.email.value == "" )
{
jAlert('Please supply a valid email address.', 'Alert Dialog');
valid = false;
}

if ( document.register.user_name.value == "" )
{
jAlert('Please choose a username.', 'Alert Dialog');
valid = false;
}

return true;

}


If I use regular JavaScript alert boxes, they pop up one by one and disappear one-by-one as the user clicks "OK" on each one. But when I switch "alert" for "jAlert," only the last field to have an error will display a box.

I.e., if all three fields are left blank, only the "user_name" jAlert box will appear.

Thanks for any guidance!

Ben Y. on Mar 28th, 2009

I believe that your plugin is having a slight problem w/ the latest jQuery release.

FireBug captures a "unrecognized expression [@href] when calling method..." error. I assume that this is related to attribute selector changes in jQuery 1.3.x.

I'm sure that a few additional tweaks will make your plugin fully 1.3.x compliant....

David P on Mar 31st, 2009

I've in my page following code :
// pseudo code
$(document).ready(function() {
... some js functions
jAlert("test1", "hello popup", function() {alert("everything works fine :)")});
$.getJSON(....
}

when I load the page, jAlert popups like it should, but the getJSON method also gets invoked. but why ? shouldn't it wait until the jAlert function returns like the alert() js method ?
I'm confused with this, because there could be situations I wouldn't want the code beneath the jAlert method to be executed until the jAlert popup disappears (the users clicks and closes the popup).

please explain.

msegmx on Apr 1st, 2009

@msegmx: Please see some of the comments above and the demo page for examples of how to use the callback function properly.

Cory S.N. LaViska on Apr 1st, 2009

ah yes, you wrote a clear response to it on Jan 26th.
thanks for your quick response.

msegmx on Apr 1st, 2009

Got a problem here with the jConfirm-function...
It doesn't pause the event, for example when confirming a click...
The example given by Matt wont work (caused by the "return false" at the end, i think)
Found this one: http://nadiana.com/jquery-confirm-plugin
So somehow it must work ;-)

But maybe i'm stucked after one day trying it out...

strizzi on Apr 2nd, 2009

@strizzi: The plugin you linked us to still relies on a callback function -- not in the confirm itself -- but you have to assign an event to the element *first*. Then, you have to call the confirm() on that element and it will utilize the callback(s) assigned to the respective event(s). In essence, there is an extra step required to use it and, in my opinion, it's bad for code clarity.

With my plugin, you can call $.alerts.confirm() (or the jConfirm shortcut function) at anytime, without having to bind it to another element. The callback function is a pretty standard jQuery practice, so it's a lot easier for someone reviewing your code to understand.

There is plenty of explanation in the comments above that explain why jConfirm() (and the other functions) can't "pause" the script from executing.

Cory S.N. LaViska on Apr 2nd, 2009

You're absolutly right - the comment of 14th february should say it all. thx!

strizzi on Apr 6th, 2009

Very nice. Your webpage states that the code is dual licensed under both GNU and MIT licenses, but the source code shows only GNU. Could you please add the MIT reference to the source. I'm afraid I cannot use GNU licensed code.

Bill on Apr 6th, 2009

@Bill: Sorry, mate! All of our plug-ins were updated last week and we obviously missed updating the license in the source. Thanks for catching that :)

Cory S.N. LaViska on Apr 6th, 2009

Thank you very much for this great piece of work!
About the onsubmit thing: What about having just a button, not type = submit and fire submit depending on the confirm result?

pp_coda on Apr 8th, 2009

Hi,

I need to integrate with JavaServer Pages, but I can't make it work. Have tried to change all $ to jQuery, but it still won't work.

How do we use Jquery with JavaServer Pages?

Lars Nielsen Lind on Apr 11th, 2009

Hi,

solved. Just downloaded the additional files from the jquery site.

Lars Nielsen Lind on Apr 11th, 2009

A solution to the jconfirm can be

<a href="#" onclick="confirm('/url/that/deletes/')">delete</a>

function confirm(url)
{
jConfirm('Are you sure you want to delete?', 'Confirmation Dialog', function(r) {
if (r) {
window.location = url
}
});
}

Tamonash on Apr 12th, 2009

Hi
jQuery Confirm work great. I am trying to add a jquery confirm box in a link. Though jquery confirm box is loaded, the browser automatically redirects to the href link. Here is the code.

<a href="page.html" onclick="return jconfirm('30 credits will be subtracted from your available credits. Do you want to continue?');">

Thanks
Sujith

Sujith on Apr 15th, 2009

Hi,

Is there any way to combine this very handy plugin with an autocomplete plugin, such as http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/ ?

Thanks,

JFlac

Jean-François on Apr 16th, 2009

thanks for the plug in, I'm using it on a classic ASP page that is also utilizing the ASP Framework developed by Christian Calderon. This plug in is indeed a great replacement for the default dialogs. Concerning IE, how can I resolve the problem that every time I scroll the window the dialog is left at the spot where it popped up? It works fine on FF, but majority of our users are using IE 6. Thanks a lot.

rhalf on Apr 20th, 2009

To kyrael and Rose on the problem of IE6 select elements.

The solution I came up with is borrowed from qTip source code (so credit to Craig Thompson) and ultimately from the bgiframe-plugin of jQuery.

I just added this

// Internet Explorer 6 ONLY
if (parseInt($.browser.version.charAt(0)) == 6) {
if ($('select, object').length) {
var html = '<iframe class="popup-bgiframe" frameborder="0" tabindex="-1" src="javascript:false" ' + 'style="display:block position:absolute; z-index:-1; filter:Alpha(Opacity=\'0\'); ' + 'top:expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+\'px\');' + 'left:expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+\'px\'); ' + 'width:expression(this.parentNode.offsetWidth+\'px\'); ' +
'height:expression(this.parentNode.offsetHeight+\'px \');"/>';

$(html).prependTo($("#popup_container"));
}
}

to the end of _show after the draggable if.

Timo on Apr 22nd, 2009

Hi,

Is it possible to change the text and title of the confirm dialog box? say I have two links, one is a logout button the other is a reset button. I want the text that appears in the confirm box to say 'Do you want to reset this?' when reset butotn is clicked, and to say 'Do you want to log out?' when the logout button is clicked. Am quite new to jequery so not sure if it's something dead simple I'm missing.

Many thanks for the work on the plug in as well!

Euan

Euan Green on Apr 30th, 2009

This is the same as another comment here but that one went unanswered.

I am using this plug-in along with netsuite so needed to remove the OK button completely since netsuite reloads the page after the button that launches jQuery is clicked. The Alert_button does not stay on the screen long enough for anyone to click OK.

Any advice?

Bowman on May 1st, 2009

@Bowman - Sorry, you'd have to modify the source code. This isn't built into the plugin.

Cory S.N. LaViska on May 1st, 2009

I'm having issues with jConfirm and IE 7, works great in FF.
What I'm doing is: jPrompt, then some checks if I find what I'm checking for I do one more confirm for the action. Problem is the jConfirm within the jPrompt does not popup on IE but works fine with FF.
Code snip:
jPrompt("Save report as: ", report[report.selectedIndex].text , "Save report", function(r){
if(r)
var reply = r;
else
var reply = "";


if(reply.length > 1) {
//code to check if a report of that name exists if so set found = true else found = false


if(found) {
jConfirm('Are you sure you want to save over '+reply, 'A report of that name already exists', function(r) {
if(r===true) {
//code to save report
}
;})

}
});

Atso Peter on May 6th, 2009

I need to execute function after the user's click in the button ok, I managed to do with jConfirm, bad I need to do with jAlert.

Celestino on May 7th, 2009

Mayor security fault - I can still access the page using the Tab button.

Sthrudel on May 13th, 2009

Please can the author review the following forum post:

http://groups.google.com/group/jquery-ui-layout/browse_thread/thread/ef0185be83f8d666

I was trying to implement this plugin in a system which used a layout plugin. The solution to my problem was that your plugin binds to the window resize and then unbinds everything!

Kindly the author of the other plugin provided me with a fix, if you could implement it so that other people don't suffer the problems I did, that would be great! :)

Phil on May 14th, 2009

how to close it using javascript?
for example :
I want to close dialog if user doesn't click any button for 10 seconds
jAlert('Please ensure something!');
setTimeout('closeDialog',10000);
function closeDialog(){
// how to close the alert dialog?
}

small on May 14th, 2009

#Phil - Thanks for your post. I've applied the fix and updated the plug-in to version 1.1.

Cory S.N. LaViska on May 14th, 2009

Cory,
This is a clean, lightweight and easy to use plugin. Have you given any thought to a progress version -- I am about to extend your code to include a version with a determinate progresss bar, and one with an indeterminate 'throbber'. Before doing this, I wanted to make sure I wasn't reinventing the wheel.

BillL on May 15th, 2009

Cory,

Is there a way to call jAlert from C#?

I have tried a variety of methods and they all work from Firefox 3.0.10, but they all fail from IE 7.

In each case, I have class variable defined as:
string jScript;
jScript = "jAlert('The total of ALL Goods cannot be greater than 10,000', 'The Total of ALL Goods Exceeds the Max Limit');";


The various methods that I have tried are

Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "goodsAlert", jScript, true);
Page.ClientScript.RegisterStartupScript(typeof(Page), "goodsAlert", jScript, true);
ScriptManager.RegisterStartupScript(Page, typeof(String), "goodsAlert", jScript, true);
Page.ClientScript.RegisterClientScriptBlock(this.Page.GetType(), "goodsAlert", jScript, true);

Richard Pack on May 20th, 2009

I'm a total noob at this stuff so bare with me...

Is there a way to fade the background (web page) in and out when the alert box appears and disappears?

Justine on May 25th, 2009

Hi, I have tried to apply this plugin, it works great, however the select input in IE6 will cover the alert, confirm dialog. There is already a comment telling that he will make the select inputs invisible, however it didn't fit my situation. I still need them to be visible. Can anyone show me a way? Thanks

Nancy on May 29th, 2009

"var pos = ($.browser.msie && parseInt($.browser.version) <= 6 ) ? 'absolute' : 'fixed';";
This should also be done for IE8 in Quirks mode.

Robin on May 29th, 2009

Simply great! I love it! I'd like to override the standard js alert() instead to call jAlert()... is it possible? Thank you!

Alessandro Marinuzzi on Jun 1st, 2009

Hi there,
I would be useful to get a compressed script like jquery.alerts-min.js or jquery.alerts-pack.js.

David on Jun 13th, 2009

Hi,

For IE7 problem, you don't have to change any condition/code. The position: fixed is working in IE7. You need to make sure that you declare your document in strict mode. Example:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">;

Thanks.

Nazwan on Jun 23rd, 2009

Hi, I use the Jalert(). Is there a way to trigger the moment, the user clicked on the OK button? I am using this for indicating erros on form validations and after the click on OK I would like to empty the form fields. Is there a way to do this?

heohni on Jun 30th, 2009

Add a comment

Name*

Email*

Never, ever sold or spammed :)

Homepage

Comment*

Sorry, plain text only :(