jQuery UI Alert Dialog as a replacement for alert() - javascript

I'm using alert() to output my validation errors back to the user as my design does not make provision for anything else, but I would rather use jQuery UI dialog as the alert dialog box for my message.
Since errors are not contained in a (html) div, I am not sure how to go about doing this. Normally you would assign the dialog() to a div say $("#divName").dialog() but I more need a js function something like alert_dialog("Custom message here") or something similiar.
Any ideas?

I don't think you even need to attach it to the DOM, this seems to work for me:
$("<div>Test message</div>").dialog();
Here's a JS fiddle:
http://jsfiddle.net/TpTNL/98

Using some of the info in here I ended up creating my own function to use.
Could be used as...
custom_alert();
custom_alert( 'Display Message' );
custom_alert( 'Display Message', 'Set Title' );
jQuery UI Alert Replacement
function custom_alert( message, title ) {
if ( !title )
title = 'Alert';
if ( !message )
message = 'No Message to Display.';
$('<div></div>').html( message ).dialog({
title: title,
resizable: false,
modal: true,
buttons: {
'Ok': function() {
$( this ).dialog( 'close' );
}
}
});
}

Building on eidylon's answer, here's a version that will not show the title bar if TitleMsg is empty:
function jqAlert(outputMsg, titleMsg, onCloseCallback) {
if (!outputMsg) return;
var div=$('<div></div>');
div.html(outputMsg).dialog({
title: titleMsg,
resizable: false,
modal: true,
buttons: {
"OK": function () {
$(this).dialog("close");
}
},
close: onCloseCallback
});
if (!titleMsg) div.siblings('.ui-dialog-titlebar').hide();
}
see jsfiddle

Just throw an empty, hidden div onto your html page and give it an ID. Then you can use that for your jQuery UI dialog. You can populate the text just like you normally would with any jquery call.

As mentioned by nux and micheg79 a node is left behind in the DOM after the dialog closes.
This can also be cleaned up simply by adding:
$(this).dialog('destroy').remove();
to the close method of the dialog.
Example adding this line to eidylon's answer:
function jqAlert(outputMsg, titleMsg, onCloseCallback) {
if (!titleMsg)
titleMsg = 'Alert';
if (!outputMsg)
outputMsg = 'No Message to Display.';
$("<div></div>").html(outputMsg).dialog({
title: titleMsg,
resizable: false,
modal: true,
buttons: {
"OK": function () {
$(this).dialog("close");
}
},
close: function() { onCloseCallback();
/* Cleanup node(s) from DOM */
$(this).dialog('destroy').remove();
}
});
}
EDIT: I had problems getting callback function to run and found that I had to add parentheses () to onCloseCallback to actually trigger the callback. This helped me understand why: In JavaScript, does it make a difference if I call a function with parentheses?

DAlert jQuery UI Plugin Check this out, This may help you

I took #EkoJR's answer, and added an additional parameter to pass in with a callback function to occur when the user closes the dialog.
function jqAlert(outputMsg, titleMsg, onCloseCallback) {
if (!titleMsg)
titleMsg = 'Alert';
if (!outputMsg)
outputMsg = 'No Message to Display.';
$("<div></div>").html(outputMsg).dialog({
title: titleMsg,
resizable: false,
modal: true,
buttons: {
"OK": function () {
$(this).dialog("close");
}
},
close: onCloseCallback
});
}
You can then call it and pass it a function, that will occur when the user closes the dialog, as so:
jqAlert('Your payment maintenance has been saved.',
'Processing Complete',
function(){ window.location = 'search.aspx' })

There is an issue that if you close the dialog it will execute the onCloseCallback function. This is a better design.
function jAlert2(outputMsg, titleMsg, onCloseCallback) {
if (!titleMsg)
titleMsg = 'Alert';
if (!outputMsg)
outputMsg = 'No Message to Display.';
$("<div></div>").html(outputMsg).dialog({
title: titleMsg,
resizable: false,
modal: true,
buttons: {
"OK": onCloseCallback,
"Cancel": function() {
$( this ).dialog( "destroy" );
}
},
});

Use this code syntax.
$("<div></div>").html("YOUR MESSAGE").dialog();
this works but it append a node to the DOM.
You can use a class and then or first remove all elements with that class.
ex:
function simple_alert(msg)
{
$('div.simple_alert').remove();
$('<div></div>').html(is_valid.msg).dialog({dialogClass:'simple_alert'});
}

Related

Jquery UI box - Takes more than 1 click to run

I am dynamically appending a <div> to the body of my webpage. This <div> does not exist on my .html page.
Within this <div> I am creating a Jquery UI YES NO box. Quite simply, it will 'do something' and close the box when YES, and just close the box when NO.
I have a working piece of code to create this box. However, frequently it takes two clicks of the YES button to work, which is very confusing. You'll see I have used a variety of methods to close the box.
$(function () {
$('body').append('<div id="dialog-confirm"></div>').click(function (e) {
e.preventDefault();
$("#dialog-confirm").dialog("open");
});
$("#dialog-confirm").dialog({
autoOpen: true,
height: 200,
width: 200,
modal: true,
title: 'Choose item?',
buttons:
{
'YES': function () {
$(this).dialog("close");
//$("#dialog-confirm").dialog("close");
//$('body').remove('#dialog-confirm');
$('#dialog-confirm').remove();
},
'NO': function () {
$(this).dialog("close");
//$("#dialog-confirm").dialog("close");
//$('body').remove('#dialog-confirm');
$('#dialog-confirm').remove();
}
}
});
});
The problem is that there is a race condition between your adding the div and attaching the click handler. Sometimes it happens before, sometimes after. That's why you get inconsistent click behavior. Try the following:
$(function() {
$('body').append('<div id="dialog-confirm"></div>');
$("#dialog-confirm").dialog({
autoOpen : true,
height : 200,
width : 200,
modal : true,
title : 'Choose item?',
buttons : {
'YES' : function() {
$(this).dialog("close");
// $("#dialog-confirm").dialog("close");
// $('body').remove('#dialog-confirm');
$('#dialog-confirm').remove();
},
'NO' : function() {
$(this).dialog("close");
// $("#dialog-confirm").dialog("close");
// $('body').remove('#dialog-confirm');
$('#dialog-confirm').remove();
}
}
});
$('#dialog-confirm').click(function(e) {
e.preventDefault();
$("#dialog-confirm").dialog("open");
});
});

Bootbox: Callback function after dismissing the dialog / Clicking on the 'X' button

The following snippet allows me to perform stuff in a callback function for the buttons that are clicked. However, how can I get a callback function, or a similar workaround such that I can perform some code when a user clicks on the 'X' button/dismisses the dialog?
bootbox.dialog({
title: "Woah this acts like an alert",
message: "Cool info for you. You MUST click Ok.",
buttons: {
sucess:{
label: "Ok",
callback: callback
}
}
});
callback(){//stuff that happens when they click Ok.}
I do not want to disable/hide the close button with
closeButton: false,
There is onEscape function for this.
bootbox.dialog({
message: 'the msg',
title: "Title",
onEscape: function() {
// you can do anything here you want when the user dismisses dialog
}
});
You can use a variable to check if the modal was hidden after a click on OK or x button / escape key
var status = false;
$('.btn').on('click', function () {
bootbox.dialog({
title: "Woah this acts like an alert",
message: "Cool info for you. You MUST click Ok.",
buttons: {
sucess: {
label: "Ok",
callback: function () {
status = true;
}
}
},
onEscape: function () {
$('.bootbox.modal').modal('hide');
}
});
});
$(document).on("hidden.bs.modal", ".bootbox.modal", function (e) {
callback();
});
function callback() {
if (!status) {
onClose();
} else {
onOK();
status = false;
}
}
function onClose() {
$('p.alert span').removeClass().addClass('text-danger').text("Dismissed");
}
function onOK() {
$('p.alert span').removeClass().addClass('text-success').text("Sucess");
}
Fiddle demo
Some people might see this as a bit of a hack-around. Although it suits me fine as all I wanted to acknowledge as a developer that someone accepted the message, which triggered the next event.
Using Bootbox.js' native confirm() method which does supply a callback action. I added an additional class as an option to the confirm button (which must be supplied on a confirm() call) with the hidden classname (E.g. Bootstap has a helper class for display:none called hidden.
This hides the confirm button, thus the Modal appears as a normal Alert box.
bootbox.confirm({
message: "Some Button Text",
buttons: {
"cancel": {
label: "<i class='fa fa-check'></i> OK - I understand",
className: "btn btn-primary"
},
//Hide the required confirm button.
"confirm": { label: "", className: "hidden" }
},
callback: function(){
//Begin Callback
alert( "Finished" );
}
});
JsFiddle Example

Variable value not updating inside dialog

I have the following simple dialog:
function confirmDialog(message, title) {
var returnvalue;
if ($("#confirmDialog").length == 0)
$('body').append('<div id="confirmDialog"></div>');
var dlg = $("#confirmDialog")
.html(message)
.dialog({
autoOpen: false,
minHeight: 50,
title: title,
show: {
effect: "explode",
duration: 250
},
hide: {
effect: "explode",
duration: 250
},
buttons: {
"OK": {
text: "OK",
class: "",
click: function () { returnvalue = true; $("#confirmDialog").dialog("close"); }
},
"Cancel": {
text: "Cancel",
class: "",
click: function () { returnvalue = false; $("#confirmDialog").dialog("close"); }
}
},
modal: true
});
$('#confirmDialog').dialog("open");
return returnvalue;
}
very simple implementation. My problem is that when I run through the script, at the end, when it returns the variable returnvalue is undefined, meaning, it did not set it to either true or false depending on which button was clicked.
I have tried setting it to var returnvalue = false; but it never gets a different value no matter which button I click.
Any help is appreciated!! Thank you!
EDIT:
I believe I noticed why the variable doesn't get set. I am calling this dialog from the click event from another dialog, after the user clicks on the "Save" button of the parent dialog, this one pops up. Now, since it is contained in a function, it does not wait for my input, meaning, it doesn't "see" that I clicked either "OK" or "Cancel". How can I fix this?
jQuery dialogs do not block execution like the built in javascript confirm() function. I can suggest two possible solutions:
Pass "ok" and "cancel" callbacks into your confirmDialog function.
Have your confirmDialog function return a promise object that you resolve after a button is clicked and have the calling function wait for that to resolve.
I prefer option 2.
I would have the button clicks trigger an event before they close the dialog, then I would listen for that event to happen in the parent process.
parent dialog opens
user clicks save
opens confirmation dialog
user closes confirmation dialog
confirmation dialog triggers "ok" or "canceled" event depending
parent dialog is listening for "ok" or "canceled" event
parent dialog reacts accordingly
confirmation dialog buttons
buttons: {
"OK": {
text: "OK",
class: "",
click: function () { $(this).trigger("ok"); $("#confirmDialog").dialog("close"); }
},
"Cancel": {
text: "Cancel",
class: "",
click: function () { $(this).trigger("cancel"); $("#confirmDialog").dialog("close"); }
}
}
parent dialog, or document.ready()
$("#confirmDialog").on({
"ok":function(event,ui){
//save work
},
"cancel":function(event,ui){
// cancel work
}
},null,null);

jQuery dialog button how to set the click event?

Ok i got this code:
$(document).ready(
function() {
$(".dialogDiv").dialog({
autoOpen: false,
modal: true,
position: [50, 50],
buttons: {
"Print page": function() {
alert("Print");
},
"Cancel": function() {
$(this).dialog("close");
}
}
}
);
$('.ui-dialog-buttonpane button:contains("Print page")').attr("id", "dialog_print-button");
$(".dialogDiv").parent().appendTo($('form'));
}
How do I assign or set a new function to the click event?
$("#dialog_print-button"). ???
Edit, This works:
$("#dialog_print-button").unbind("click").click(
function () {
alert("new function that overide the old ones")
}
)
Tried to find how to do in the jQuery documentation but I think it's hard to find around in the documentation. Especially when new to javaScript and the jQuery libary.
Edit, A fast way to get help is to go to jQuery irc channel :D
I think this would help:
$(".dialogDiv").dialog("option", "buttons", {
"Print page": function() { /* new action */ },
"Cancel": function() { $(this).dialog("close"); }
});
Because buttons property sets all the buttons, you have to include cancel button handler.
$("#Print page").click(function () {
...
});
Or maybe it should be
$("#dialog_print-button").click(function () {
...
});
jQuery UI dialog buttons now supports the "id" attribute natively.
$("#dialog-form").dialog({
autoOpen: false,
height: "auto",
width: 300,
buttons:
[
{
text: "Create Revision",
id: "btnCreateRev",
click: function () {
//code for creating a revision
}
},
{
text: "Cancel",
id: "btnCancel",
click: function () { $(this).dialog("close"); },
}
]
});
You put the code within the button section:
...
buttons: {
"Print page": function() {
//here you execute the code or call external functions as needed
}
Once you click the button on the Dialog, that code is automatically invoked.
Therefore you insert there directly the code that implements your logic.

How to refresh changed buttons in jQuery UI dialog?

I have a jQuery UI dialog which is initialized
$('#jqDialog').dialog({
autoOpen: false,
modal: true,
resizable: false,
buttons: { 'Ok': function () { $(this).dialog('close'); } },
});
and then I want to change the buttons programatically w/o re-initializing the plugin instance.
$('#jqDialog')
.dialog('options',
{
buttons: {
'Ok': function () {
$(this).dialog('close');
store(id);
},
'Cancel': function () { $(this).dialog('close'); }
}
})
.dialog('open');
When the dialog window is opened it still have the original button. With the Button plugin you have to call .button("refresh"). Is there a similar method that needs to be called with the Dialog plugin?
What you have just needs a tweak, the method name is 'option' (no s) like this:
.dialog('option',
This works even when the dialog's open, you can test it out here.
You could destroy the dialog first by calling $dlg.dialog('destory'). and reevaluate the dialog you want.
The only wrong thing in your code is the use of the word options instead of option as in the following code
$("jqDialog").dialog("option", "buttons",
{
"Ok": function() {
$(this).dialog("close");
}
});

Categories

Resources