I am trying to build a generic function that I can invoke from anywhere in the application by passing custom parameters to the jQuery UI confirmation dialog. I have been searching and trying different things but the following is the logic I would like to use. What am I doing wrong? Any help is much appreciated.
Here is the function:
function popDialog(h, w, deny_btn, confirm_btn, confirm_title, confirm_message, deny_action, confirm_action) {
var newDialog = $('<div id="dialog-confirm">\
<p>\
<span class="ui-icon ui-icon-alert" style="float: left;margin: 0 7px 60px 0;"></span>\
' + confirm_message + '\
</p>\
</div>');
newDialog.dialog({
resizable: false,
height: h,
width: w,
modal: true,
autoOpen:false,
title: confirm_title,
buttons: [
{text: deny_btn: click: function() {deny_action}},
{text: confirm_btn: click: function() {confirm_action}}
]
});
}
Here is the call:
$("#cancel").click(function(e) {
popDialog("210", // height
"350", // width
"No", // deny_btn
"Yes", // confirm_btn
"Confirm Cancel", // confirm_title
"Are you sure you would like to cancel? Changes will not be saved.", // confirm_message
$('#dialog-confirm').dialog('close'), // deny_action
window.location = '/some/location/index/<?= $class->getClassid() ?>'); //confirm_action
});
So there are a number of issues with this, and I think the best way to tackle them all would be a small refactor. I put the code into jsfiddle for testing and tinkering, and here's what came out:
http://jsfiddle.net/BDh2z/1/
Code is reproduced below:
function popDialog(opts) {
var newDialog = $('<div id="dialog-confirm"><p>'+opts.message+'</p></div>');
if (!$('#dialog-confirm').length){ $('body').append(newDialog); }
newDialog.dialog({
resizable: false,
modal: true,
title: opts.title,
height: opts.height,
width: opts.width,
buttons: opts.buttons
});
};
So above is the new function definition. Things simplified a good amount. Let's go over the changes:
function accepts a options object rather than a bunch of args for clarity
modal html is more simple and clear
autoOpen: false removed, as this prevents the modal from opening without an open() call
button syntax was completely borked in your example, fixed that up and delegated the buttons object to the call, their syntax is quite clean anyway.
actually adds the modal to the html, but only adds it once
Now here's the call:
popDialog({
width: 300,
height: 150,
title: 'testing modal',
message: 'look it worked!',
buttons: {
cancel: function(){ $(this).dialog('close') },
confirm: function(){ $(this).dialog('close') }
}
});
Much cleaner here and easier to understand, mostly because of the fact that we now accept an object rather than a bunch of args. The only issue I found was a weird fluke where jquery UI seems to be collapsing the content section, so I dropped an ugly fix for that in the css of the jsfiddle. This seems to be an issue with jquery UI, but I'll continue to look into it.
This is totally functional in the jsfiddle and looking nice, let me know if there's anything confusing here or if this doesn't exactly solve your issue : )
I think the problem is that you are passing the return value of:
$('#dialog-confirm').dialog('close')
and
window.location = '/some/location/index/<?= $class->getClassid() ?>'
to your popDialog function. You want to do this instead:
Function:
buttons: [
{text: deny_btn, click: deny_action},
{text: confirm_btn, click: confirm_action}
]
Call:
$("#cancel").click(function(e) {
popDialog("210", // height
"350", // width
"No", // deny_btn
"Yes", // confirm_btn
"Confirm Cancel", // confirm_title
"Are you sure you would like to cancel? Changes will not be saved.", // confirm_message
function() { $('#dialog-confirm').dialog('close') }, // deny_action
function() { window.location = '/some/location/index/<?= $class->getClassid() ?>') }; //confirm_action
});
That way you are passing functions to popDialog, and not values.
Just to explain the multi-line problem (can't with comments, but can with answers):
var bad = 'Invalid
syntax';
--
var good = 'Valid' +
'syntax';
Related
How would you override jQuery UI's default functionality so that whenever I set a new title for a dialog - it adds xxx in front of it? So $("#any_dialog_id").dialog("option", "title", "yyy") would set title to xxxyyy.
$().ready(function(){
$("#dialog").dialog();
$(".ui-dialog-title").before("xxx");
// I add the line //
$("#any_dialog_id").dialog("option", "title", "yyy");
});
But he show yyyxxx not xxxyyy
What I have to do, to make it work??
Thanks...
There are many ways you could do this.
The very simplest is to run your line $(".ui-dialog-title").before("xxx"); AFTER each call to opening a dialog. You cannot merely run it once and expect it to re-run on later dialog calls.
Another way to do this is to modify the jquery code. But I HIGHLY disrecommend doing that.
If I were to really want to systematically apply a prefix, I would make a helper function or wrapper that do this for me and call it instead of the jquery dialog directly.
Here is an example of what you might do and I have included a jsfiddle link as well (http://jsfiddle.net/stdw6j5q/1/):
HTML:
<div id="idDiv_MyDialog">Hi 1!</div>
<div id="idDiv_MyDialog2">Hi 2!</div>
<div id="idDiv_MyDialog3">Hi 3!</div>
<div id="idDiv_MyDialog4">Hi 4!</div>
JAVASCRIPT:
jDialog = function(options) {
// THE WRAPPER TAKES TWO EXTRA OPTIONS TO IDENTIFY THE DIALOG AND THE TITLE PREFIX TO USE
// I SET A DEFAULT SELECTOR IF NOTHING IS PASSED IN
var _dialog = options && options.dialog ? options.dialog : '#idDiv_MyDialog';
// HERE YOU CAN SET A DEFAULT PREFIX
var _titlePrefix = options && options.titlePrefix ? options.titlePrefix : 'XYZ: ';
// UPDATE THE TITLE OPTION
options.title = _titlePrefix + options.title;
// PASS THROUGH ALL YOUR NORMAL OPTIONS TO THE DIALOG
$(_dialog).dialog(options);
// THIS RETURNS A HANDLE/REFERENCE TO THE DIALOG CREATED
return $(_dialog);
}
$(function() {
// CALL YOUR WRAPPER WHEN YOU NEED TO CREATE/MOD THE DIALOG
$myDialog1 = jDialog({
title: 'Hey Jude',
close: function(event, ui) { $myDialog2.dialog('open'); }
});
$myDialog2 = jDialog({
dialog: '#idDiv_MyDialog2',
title: 'Don\'t let me down',
autoOpen: false,
close: function(event, ui) { $myDialog3.dialog('open'); }
});
$myDialog3 = jDialog({
dialog: '#idDiv_MyDialog3',
title: 'Take a sad song',
autoOpen: false,
close: function(event, ui) { $myDialog4dialog('open'); }
});
$myDialog4 = jDialog({
dialog: '#idDiv_MyDialog4',
title: 'And make it better',
autoOpen: false
});
});
You can set an event to run whenever a dialog is created that adds the title.
$(document).on('dialogcreate', function(){ // let it bubble up
$(".ui-dialog-title", this).before("xxx"); // add "xxx" before the title of this dialog
});
I have a button's onclick set to use the following function EditContact. This function sets up a jquery dialog, gets the data from the server and displays it. Everything works but I would like to get it to work a little better. Right now the empty dialog pops up for the time it takes the code to go and fetch the content from the server then the dialog populates with the content. My question is how can I get the dialog to not pop up until the content has been received.
function EditContact() {
$('#editContactView').dialog({
modal: true,
width: 'auto',
position: ['top', 'center'],
resizable: false,
autoOpen: false,
open: function (event) {
var szAction = "Content url for this example";
$(this).load(szAction,
function (response, status, xhr) {
$('#editContactView').dialog('open');
return false;
});
}
});
$('#editContactView').dialog('open');
}
I think you should be able to essentially turn what you have inside out and and open the dialog on $().load() completion. Something like this might do it:
function editContact() {
var szAction = "Content url for this example";
$(this).load(szAction, function (response, status, xhr) {
$('#editContactView').dialog({
modal: true,
width: 'auto',
position: ['top', 'center'],
resizable: false
});
});
}
Edit:
Notice I removed the {autoOpen: false}. This will create it and open it in one shot after you receive the content.
You are calling .dialog('open') twice: in the end of the code and in the callback for the loading.
As JavaScript is asynchronous, it runs the line $('#editContactView').dialog('open'); in the end before the data is received.
Removing this line should solve the problem.
I'm opening a dialog using a .load function and then I want to grab the values from the fields in the dialog defining the variables outside the dialog function, but it returns undefined, so my question is, how do I define the variables outside the dialog function to use it inside it,
An example what I want to do.
First I request the dialog:
$( '#dialog-form' ).load('table_models/add_to_table.php',function(){
$( '#dialog-form' ).dialog('open');
});
Now I define the variables and the dialog popup:
$(function() {
var sku = $( "#sku" ),
fba_sku = $( "#fba_sku" ),
asin = $( "#asin" ),
$( "#dialog-form" ).dialog({
title: 'New Product',
autoOpen: false,
height: 'auto',
width: 'auto',
modal: true,
buttons: {
"Done": function() {
// I want to get the var sku, fba_sku, asin here
}
},
}
}
I hope you understand what I want to do, if not I will try to explain it better,
Thanks
EDIT
The .load function being requested from a button on page, then the dialog function is on external JS file, there I want to define first the var of the fields from the dialog form and reuse it for all functions on this page.
Try defining the function outside the object, like so:
var cb = function() { /* stuff with sku, fba_sku, asin */ };
$("#dialog-form").dialog({
...
buttons:{"Done":cb}
});
Your understanding of "'Now' I define [...]" may be flawed–it's unclear where the ready function is defined. .load is asynchronous and will complete at an arbitrary time in the future.
Get the element values in the "Done" function so they're filled with the most recent values.
I have a jQuery UI dialog that gets a line of text. If this text is not contained in a localStorage dictionary, I insert it into the dictionary. If it is present, I want to give the user the option not to overwrite the existing entry in the "ok" handler.
Because jQuery UI dialogs are stateful and persist across multiple calls unless explicitly removed (AFAICT), I'm not seeing a clear path to presenting the "are you sure you want to nuke your previous entry?" alert without resorting to ... uh ... alert.
The question, succinctly stated: Can you create a confirmation box from inside a jQuery UI Dialog?
Thanks.
I have not used jQuery UI Dialog, but you can always create your own html elements and do whatever you wish with them, including layering them on top of the jQuery dialog.
I guess you could have googled something to find these links:
Anyways have it and make fun:
JQuery Dialogs
Jquery Confirmation
Cheers!!!
Ok, it turned out the best way I found to handle this was using closures. Like this (pseudo-code):
getThingieName: handler(function() {
var $dialog;
$dialog = $('<div id="thingie-name-dialog" class="ui-widget"></div>').html("<p>Enter a name for this thingie</p>\n<input type=\"text\" id=\"dlg-thingie-name\" style=\"width: 80%\" />").dialog({
autoOpen: false
}, {
title: 'enter a name',
modal: true,
buttons: {
Add: function() {
var value = $('#dlg-thingie-name').val();
$(this).dialog('close');
$('#thingie-name-dialog').remove();
return handler(value); // <= closure to handle the onAdd
},
Cancel: function() {
$(this).dialog('close');
return $('#thingie-name-dialog').remove();
}
}
});
return $dialog.dialog('open');
}),
getConfirmation: function(message, handler) {
var $dialog;
$dialog = $('<div id="confirmation-dialog" class="ui-widget"></div>').html("<p>" + message + "</p>").dialog({
autoOpen: false
}, {
title: 'confirm overwrite',
modal: true,
buttons: {
Ok: function() {
$(this).dialog('close');
$('#confirmatio-dialog').remove();
return handler(true); // <= closure to handle onOk
},
Cancel: function() {
$(this).dialog('close');
$('#Thingie-name-dialog').remove();
return handler(false); // <= closure to handle onCancel
}
}
});
return $dialog.dialog('open');
}
// Calling sequence
Snippets.getSnippetName(function(value) {
if (value == null) return false;
if (localStorage.getItem(value)) {
getConfirmation("This thingie, " + value + ", already exists. Overwrite?", function(response) {
if (response) return localStorage.setItem(value, snippet);
});
} else {
localStorage.setItem(value, snippet);
}
}
This may not be the optimal code, but it does make the triggering of the dialogs dependent on the button push by embedding them in the handlers.
How can we create a confirmation alert in javascript with a save and discard button in it?
If we use the code
confirm('Do you want to save it?');
We will get an alert box with ok cancel.
How can we make the text of ok button as save and the other as discard?
You cannot modify the default javascript method "confirm". But, you can override it, for example, with jQuery UI dialog:
window.confirm = function (message) {
var html = "<div style='margin:20px;'><img style='float:left;margin-right:20px;' src='/img/confirm.gif' alt='Confirm'/><div style='display:table;height:1%;'>" + message + "</div></div>";
$(html).dialog({ closeOnEscape: false,
open: function (event, ui) { $('.ui-dialog-titlebar-close').hide(); },
modal: true,
resizable: false,
width: 400,
title: "Confirmation",
buttons: {
"Save": function () {
//Do what you need
},
"Cancel": function () {
$(this).dialog("close");
}
}
});
}
this is not possible
more answers
Connect some of the tons JS framework. For example jQuery+UI
Overwrite window.confirm method, by makin it as wrapper to your favorite JS UI framework.
PROFIT!!!