How would I reference a dynamically created jQuery dialog box so I can close it programatically? - jquery-ui

When I began using jQuery a little over a year ago, I needed to load remote content into a pop-up dialog box. After scouring the internet and trying out several suggested methods for doing this, I came upon a function that worked exactly as I needed it to. However, one problem I've never solved is how to reference the dynamic dialog box so it can be closed from an outside function.
Here's the function that creates the dialog box, appends it to the body, and then loads a page into it:
function openDynamicDialog() {
var url = 'mypage.cfm';
var dialog = $('`<div style="display:hidden"></div>`').appendTo('body');
$(dialog).dialog({
autoOpen: true,
title: 'My Title',
resizable: true,
modal: true,
width: 250,
height: 100,
close: function(ev, ui) {
$(this).remove(); // ensures any form variables are reset.
},
buttons: {
"Close": function(){
$(this).dialog("close");
}
}
});
// load remote content
dialog.load(
url,
{},
function (responseText, textStatus, XMLHttpRequest) {
dialog.dialog();
}
);
//prevent the browser from following the link
return false; };
I've considered giving that hidden div a hard-coded id value, but I'm not sure if there are drawbacks to that approach.
Any suggestions would be most appreciated.

I would use a hard-coded id value for the <div> element.

No there shouldn't be any drawback giving it an ID. If you fear of some kind of conflicts then you can give it a class instead, or save a reference to the div object in a global variable.

Well im not sure what the return false is at the end. so if you don't need that, do this:
function openDynamicDialog() {
var url = 'mypage.cfm';
var dialog = $('<div>').css('display','none').appendTo('body');
$(dialog).dialog({
autoOpen: true,
title: 'My Title',
resizable: true,
modal: true,
width: 250,
height: 100,
close: function(ev, ui) {
$(this).remove(); // ensures any form variables are reset.
},
buttons: {
"Close": function() {
$(this).dialog("close");
}
}
});
// load remote content
dialog.load(
url, {}, function(responseText, textStatus, XMLHttpRequest) {
dialog.dialog();
});
return dialog;
}
//call it like this:
var dialog = openDynamicDialog();
//..code
//close it:
dialog.dialog('close');
OR
if you still need that return false, you can do this on the var dialog line of the function:
var dialog = $('<div>', {id: 'dialog_id'}).css('display','none').appendTo('body');
and then reference it from the outside:
var dialog = $('#dialog_id');

Related

Error: cannot call methods on dialog prior to initialization; attempted to call method 'open'

Just a little preface... I am fairly new to jQuery so if something looks wrong or redundant please feel free to offer any helpful suggestions.
Now for the issue. I have 2 modals that are initiated from 2 separate links on the page.
The first modal was fairly problem free. It is a simple form that posts back to the same page. If you are wondering what the items in the "close:" section are, they are form fields that I want to clear the values on when the dialog is closed.
Once I added the second one I have had problems. This modal calls a coldfusion page into a modal to display pictures. The problems occur after opening up the second one. I can not close the second modal from the "close" button. I get the following error.
Error: cannot call methods on dialog prior to initialization; attempted to call method 'close'
I have to close it from the "x" in the upper right hand corner of the modal. After I close it, I get an error when trying to open up the first on.
Error: cannot call methods on dialog prior to initialization; attempted to call method 'open'
Here is the code for it.
$(document).ready(function() {
$(".dig").click(function() {
//based on which we click, get the current values
var cItemName = $("#checklistItemName").attr( "title");
var c2id = $("#check2id").attr( "title");
$("#ItemName").html(cItemName);
$("#ItemID").html(c2id);
$("#objCheckItemName").val(cItemName);
$("#objCheck2ID").val(c2id);
console.log(cItemName);
console.log(c2id);
});
$( "#image-form" ).dialog({
autoOpen: false,
height: 450,
width: 650,
modal: true,
buttons: {
"Submit": function() {
$('#mForm').submit();
return true;
},
Cancel: function() {
$( this ).dialog( "close" );
}
},
close: function() {
$('#defaultSectionName')
.val('');
$('#defaultSectionDesc_hidden')
.val('');
$('#Photo')
.val('');
$('#objCheck2ID')
.val('');
$('#Check21')
.val('');
},
zIndex: 500
});
The next piece of code is where I believe the problems are occurring.
$( "#image_trigger" )
.click(function() {
$( "#image-form" ).dialog( "open" );
});
var dlg=$('#register').dialog({
title: 'Case Pictures',
resizable: true,
autoOpen:false,
modal: true,
hide: 'fade',
width:650,
height:450,
buttons: {
close: function() {
$( this ).dialog( "close" );
}
},
zIndex: 500
});
$('#reg_link').click(function(e) {
e.preventDefault();
var linkurl=('assets/includes/modalPictures.cfm' + '?'
+ 'id=' + $("#objCheck2ID").val()
);
dlg.load(linkurl, function(){
dlg.dialog('open');
});
});
jQuery UI: 1.10.1
jQuery: 1.9.1
Server Side: Coldfusion
The HTML is pretty extensive. If you need to see any part of it please let me know. Thanks for your help!
Upper case?
Close: function() {
You have to initialize your jquery dialog before calling the open function.
<script type="text/javascript">
$(document).ready(function () {
initializeDialog();
});
</script>
And change your js file to have the dialog code in initializeDialog() function.
function initializeDialog(){
$("#your-dialog-id").dialog({
autoOpen: false,
buttons: {
"Cancel": function() {
$(this).dialog("close");
}
},
modal: true,
resizable: false,
width: 600px,
height: 400px
});
}
Thanks #bpjoshi

Pass a variable to JQuery UI dialog

I am deleting a record using PHP. I want to use a JQuery UI dialog to confirm the action, but I dont know how to pass a variable (my RecordID) to the redirect URL function, or allow the URL to access window.location.href.
$("#confirm" ).dialog({
resizable: false,
autoOpen: false,
modal: true,
buttons: {
'OK': function() {
window.location.href = 'url and myvar??';
$( this ).dialog( "close" );
},
'Cancel': function() {
$( this ).dialog( "close" );
}
}
});
$("#delete").click(function() {
$("#confirm").dialog( "open" ).html ( "Are U Sure?" );
return false;
});
HTML
<a href='index.php?recordid=$row[recordid]' id='delete'>DELETE</a>
Is there a good way to do this?
You can try using the .data() method to store data for you. Take a look at this answer
Passing data to a jQuery UI Dialog
For example to pass a variable, you can store it using the data function, before opening the dialog
$("#dialog_div")
.data('param_1', 'whateverdata')
.dialog("open");
Then you can get this back by:
var my_data = $("#dialog_div").data('param_1')
You want to change the configuration of the dialog on click (in this case, the behaviour of the Ok button). For that your have many solutions all of them ugly (imo). I would advice generating a dialog on the fly, and destroying it once it has been used, something like this:
$("#delete").click(function(ev) {
ev.preventDefault(); // preventDefault should suffice, no return false
var href = $(this).attr("href");
var dialog = $("<div>Are you sure?</div>");
$(dialog).dialog({
resizable: false,
autoOpen: true,
modal: true,
buttons: {
'OK': function() {
window.location = href;
$( this ).dialog( "close" );
},
'Cancel': function() {
$( this ).dialog( "close" );
}
},
close: {
$( this ).remove();
}
});
});
Or even better, encapsulate the confirm dialog into a function so that you can reuse it, like so:
function confirmDialog(msg) {
var dialog = $("<div>"+msg+"</div>");
var def = $.Deferred();
$(dialog).dialog({
resizable: false,
autoOpen: true,
modal: true,
buttons: {
'OK': function() {
def.resolve();
$( this ).dialog( "close" );
},
'Cancel': function() {
def.reject();
$( this ).dialog( "close" );
}
},
close: {
$( this ).remove();
}
});
return def.promise();
}
And then use it like so
confirmDialog("are your sure?").done(function() {
window.location = $(this).attr("href");
}).fail(function() {
// cry a little
});
You may have to check if the deferred object has been rejected or resolved before you close the dialog, to ensure the confirm rejects on close (and not just on pressing the 'Cancel' button). This can be done with a def.state() === "pending" conditional.
For more information on jquery deferred: http://api.jquery.com/category/deferred-object/
Deleting actions probably shouldn't be done using a GET, but if you wanted to do it that way I would recommend using the $.data in jQuery so each link had a data-record-id attribute. Then on click of one of the links, it pops up the dialog and when confirmed it adds that to the URL, and redirects.
Example:
$(function(){
$(".deleteLink").click(function(){
var id = $(this).data("record-id");
var myHref = $(this).attr('href');
$("#confirmDialog").dialog({
buttons:{
"Yes": function()
{
window.location.href = myHref + id;
}
}
});
});
});
<a class="deleteLink" data-record-id="1">Delete</a>
...
<div id="confirmDialog">
<p>Are you sure?</p>
</div>
HTML
<a data-title="Title" data-content="content" data-mydata="1" class="confirmation-dialog" href="#">Link</a>
JS
$('.confirmation-dialog').confirm({
buttons: {
Yes: function(){
console.log(this.$target.attr('data-mydata'));
No: function(){
}
}
});

jQueryUI Datepicker in Dialog auto focus in IE9

I'm able to load and reopen jQueryUI Dialogs with a Datepicker as the first element in all browsers I've tried ... except IE 9.
If a Datepicker is the first element to receive focus when the Dialog opens, the Datepicker will auto launch. I'm able to suppress this behavior in FireFox and Chrome. IE 9 still launches the Datepicker on creation.
My open and close function for the Dialog are:
open: function (event, ui) {
$('#Date').blur(); // kill the focus
if ($('#Date').hasClass('hasDatepicker')) {
$("#Date").datepicker('enable');
}
else {
$("#Date").datepicker();
}
},
close: function (event, ui) {
$("#Date").datepicker('disable');
}
Here is the 'click' code
var dialogs = {};
$('#clicker').click(function (e) {
if (!dialogs['dlg']) {
loadAndShowDialog('dlg');
} else {
dialogs['dlg'].dialog('open');
}
});
var loadAndShowDialog = function (id) {
dialogs[id] = $('#dlg').clone().find('#ChangeMe').attr('id', 'Date').end()
.appendTo(document.body)
.dialog({ // Create the jQuery UI dialog
title: 'Testing',
modal: true,
resizable: true,
draggable: true,
width: 300,
open: see above
close: see above
};
jsfiddle showing this IE9 problem http://jsfiddle.net/stocksp/DdRLp/8/
What can I do to get IE to behave, short of not placing the Datepicker as the first element?
I don't have IE9 available at home so give this a try: http://jsfiddle.net/DdRLp/10/
I added a class to the datepicker input to make it easier to grab.
$(function() {
$(document).on("dialogcreate", "#dlg", function() {
$(".date_picker").datepicker();
$(".date_picker").datepicker("disable");
});
var dialogs = {};
$('#clicker').click(function(e) {
if (!dialogs['dlg']) {
loadAndShowDialog('dlg');
} else {
dialogs['dlg'].dialog('open');
}
});
var loadAndShowDialog = function(id) {
dialogs[id] = $('#dlg').clone().find('#ChangeMe').attr('id', 'Date').end().appendTo(document.body).dialog({ // Create the jQuery UI dialog
title: 'Testing',
modal: true,
resizable: true,
draggable: true,
width: 300,
open: function(event, ui) {
$("div#dlg form input").blur(); //takes focus off inputs
$(".date_picker").datepicker("enable");
},
close: function(event, ui) {
$(".date_picker").datepicker("disable");
}
});
};
});

Using zClip on click event of a jQuery UI Dialog button

I want to use a jQuery zClip plugin in jQuery UI dialog button, but I don't know how to adapt in this case. Anyone can help me?
Thank you in advance!
$.ajax({
url: '/music/lyrics/' + hash,
success: function (data) {
data = jQuery.parseJSON(data);
$('#dialog-modal').html(data.lyrics);
$('#dialog:ui-dialog').dialog('destroy');
$('#dialog-modal').dialog({
modal: true,
resizable: false,
title: 'Lyric: ' + data.song,
width: 500,
height: 400,
buttons: {
'Copy' : function () {
// use zClip to copy $('#dialog-modal').text() here
}
}
});
},
error: function (msg) {
alert(msg);
}
});
I would ignore the normal way dialog buttons handle actions, and separately use the way zClip handles actions. Something like this:
$.ajax({
url: '/music/lyrics/' + hash,
success: function (data) {
data = jQuery.parseJSON(data);
$('#dialog-modal').html(data.lyrics);
$('#dialog:ui-dialog').dialog('destroy');
$('#dialog-modal').dialog({
modal: true,
resizable: false,
title: 'Lyric: ' + data.song,
width: 500,
height: 400,
buttons: {
'Copy' : function () { return true; }
}
});
$('#dialog-modal ui-button:contains(Copy)').zclip({
path:'../whatever/ZeroClipboard.swf',
copy:$('#dialog-modal').text()
});
},
error: function (msg) {
alert(msg);
}
});
Assuming you are using jQuery 1.8+, you can specifiy your buttons in a different way to add IDs to them:
$("#mydialog").dialog({
...
buttons : [{
text: "Close",
click: function() {
$(this).dialog("close");
}
},{
text: "Copy to clipboard",
id: "copyButton", // here is your ID
click : function() {
alert("Sorry, copy not supported in your browser, please copy manually.");
}
}]
...
});
//after .dialog("open");
$("#copyButton").zclip({
...
clickAfter: false // dont propagate click: will suppress unsupported warning
...
});
The only issue I have is that it seem you can only mount zclip on visible buttons, so I do the zclip() call inside the handler for the button that opens the dialog

jquery-ui, Use dialog('open') and pass a variable to the DIALOG

I have the following JS:
$('#listeditdialog').dialog('open');
Which opens the following dialog:
$('#listeditdialog').dialog({
autoOpen: false,
resizable: false,
position: ['center',150],
width: 450,
open: function(event, ui) {
$("#listeditdialog").load("/projects/view/tasks/ajax/?listid=" + XXXX);
},
close: function(event, ui) {
$("#listeditdialog").html('<p id="loading"> </p>');
}
});
My Question is when I use the dialog open function in another JS function, how can I pass a listID variable which I would get fom the click even bind that fired the dialog open func.
Thanks!
If I understand you right, you want to have data that you have access to when you call $('#listeditdialog').dialog('open')
that's available when the open event fires?
Something like this could help:
// where dialog is opened
$('#listeditdialog').data('listID', listIDVarOrSimilar); //assign the ID for later use
$('#listeditdialog').dialog('open')
// dialog definition
$('#listeditdialog').dialog({
autoOpen: false,
resizable: false,
position: ['center',150],
width: 450,
open: function(event, ui) {
var $led = $("#listeditdialog");
$led.load("/projects/view/tasks/ajax/?listid=" + $led.data('listID'); //use the previously saved id
},
close: function(event, ui) {
$("#listeditdialog").html('<p id="loading"> </p>');
}
});`
http://api.jquery.com/data/

Resources