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");
}
});
Related
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");
});
});
I'm able to get the dialog to appear when I click "Reject Request", but the dialog won't close and I see an error in the console when I click Cancel or OK. "Uncaught TypeError: Cannot read property 'apply' of undefined"
HTML:
<button id="btn-reject" class="btn btn-danger" type="submit" style="float: right;">Reject Request</button>
<div id='reject-dialog' title='Confirmation Required'>Reject Request?</div>
JQuery:
<script type="text/javascript">
$(document).ready(function () {
$("#reject-dialog").dialog({
autoOpen: false,
modal: true,
buttons: {
"Confirm": {
text: "OK",
id: "confirm-reject"
},
"Cancel": {
text: "Cancel",
id: "cancel-reject"
}
}
});
$("#btn-reject").click(function (e) {
e.preventDefault();
$("#reject-dialog").dialog('open');
});
$('#cancel-reject').click(function () {
$("#reject-dialog").dialog('close');
console.log('confirm');
});
$('#confirm-reject').click(function () {
$("#reject-dialog").dialog('close');
console.log('reject');
});
}); //dom
</script>
JQuery versions:
you are binding to buttons that don't exist yet on document.ready.
instead you can tell the dialog what callback to trigger while creating the buttons.
Update:
according to the Jquery-ui documentation, dialog buttons options are accepted in one of the two following formats:
1) Object: The keys are the button labels and the values are the callbacks for when the associated button is clicked.
2) Array: Each element of the array must be an object defining the attributes, properties, and event handlers to set on the button.
i updated the code to reflect that.
code
<script type="text/javascript">
$(document).ready(function () {
var dialogDiv = $("#reject-dialog");
dialogDiv.dialog({
autoOpen: false,
modal: true,
buttons: [
{
text: "OK",
id: "confirm-reject",
click: function() {
dialogDiv.dialog("close");
console.log('confirm');
}
},
{
text: "Cancel",
id: "cancel-reject",
click: function(){
dialogDiv.dialog("close");
console.log('reject');
}
}
]
});
$("#btn-reject").click(function (e) {
e.preventDefault();
dialogDiv.dialog('open');
});
}); //dom
</script>
You need to use .on()'s event delegation since the buttons don't exist when the code is executed.
For example, change:
$('#cancel-reject').click(function () {
$("#reject-dialog").dialog('close');
console.log('confirm');
});
to:
$(document).on('click','#cancel-reject', function () {
$("#reject-dialog").dialog('close');
console.log('confirm');
});
jsFiddle example
Ideally you want to bind to an element that already exists on the page that's closer than document for better performance.
You need to inform a click function, even you need to bind a click handler after the create the dialog. I think this happens because Jquery tries to execute the attribute click through apply native js function and, if you don't define it, js try to execute apply in a undefined.
So, I suggest that you define an empty function (or jQuery.noop):
"Confirm": {
text: "OK",
id: "confirm-reject",
click: function(){} // or jQuery.noop()
}
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);
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'});
}
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.