I am using jquery ui dialog, I download it from jquery ui website, version is jquery-ui-1.10.2.custom.min.js, and jquery is jquery-1.9.1.js which is bundled with jquery ui js, but now I am encountering a question: when dialog is opened and click save button, I want the dialog to be closed, here is my code:
$(function(){
$("#dialog-form").dialog({
autoOpen: false,
height: 350,
width: 450,
modal: true,
buttons: {
"save": function() {
if(!checkDept()){
return ;
}
$.post('dept_save.do',
{'dept.deptId':$("#dialog_dept_deptId").val(),
'dept.deptName':$("#dialog_dept_deptName").val(),
'dept.manager':$("#dialog_dept_manager").val(),
},function(data, status, xhr){
if(status == 'success'){
alert('save success');
$(this).dialog("close");
}else{
alert('error:'+data);
}
}
,"json");
}
},
close: function() {
$(this).dialog("close");
}
});
/* to open dialog*/
$("#add").click(function(){
$("#dialog-form").dialog("open");
});
now when I close the 'save success' popuped dialog, dialog-form
dialog was not closed, and an error occurs:
Uncaught Error: cannot call methods on dialog prior to initialization; attempted to call method 'close' jquery-1.9.1.js:507.
and there is another error:
Uncaught SyntaxError: Unexpected token o jquery-1.9.1.js:541
thanks.
You are losing the context of this
once you are inside of $.post()
.
Before your $.post, save the context this
in a variable inside of that save button function.
$('#dialog-form').dialog({
// .....
buttons: {
'save': function() {
var $this = $(this);
// -this- is still the original context
// of $("#dialog-form")
$.post({
/// ...
$this.dialog('close'); // <-- used here
});
}
}
});
When you initialize a dialog by calling the .dialog(options)
method, a new dialog is created, but it's not associated to the original div that you want to convert into dialog (the '#dialog-form' in your sample code). The dialog(options)
function returns the element containing the dialog data. So, if you do it this way:
var myDialog = $("#dialog-form").dialog(options);
You can then call the open method like this:
myDialog.dialog('open');
If you want to find the element contianing the dialog, it's the closest div with "ui-dialog-content" class:
var myDialog = $('#dialog-form').closest('div.ui-dialog-content');
The dialog data is the uiDialog
data which you'll see if you look at this element data:
myDialog.data();
$(this)
isn't targeting the dialog inside of $.post
, you'll need to store a reference to it.
var self = this; // add this
$.post(..., function(){
$(self).dialog("close"); // modify this to use self
I had to do the following to get my dialog closed.
$("#Note").dialog({
autoOpen: true,
modal: true,
create: function (e, ui) {
//
},
open: function () {
//
},
buttons: {
//
$(".ui-dialog-titlebar-close").trigger('click');
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With