51
votes

I am suddenly getting this error from jQuery :

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

Plugins

 <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
 <script src="http://code.jquery.com/ui/1.9.1/jquery-ui.js"></script> 

jQuery code

I am getting those messages in the following function:

$(document).ready(function() {
  if ($('#results').html().length != 0) {
    alert('has information');

    $('#dialog').dialog({
      modal: true,
      buttons: {
        Ok: function() {
          // If I use $(this).dialog($(this)).dialog('close'), the UI is displayed,
          // however I do not see the OK button and no errors 
          $(this).dialog('close');
        }
      }
    });
  } else {
    alert('has no data');
  }
});

HTML

<div id="dialog" title="Server Response">
  <p><span class="${icon}" style="float: left; margin: 0 7px 50px 0;"></span>
    <label id="results">${results}</label>
  </p>      
</div>
20
I'm not getting this error: jsfiddle.net/ztPUj. But the fiddle uses jQuery UI 1.9.2, if that makes any difference. If not, some other code, which you did not post, must cause the problem and if you don't provide more information, we won't be able to help you.Felix Kling
Thats it jQuery UI 1.9.2 and it worked you can include an answer for me to acceptdevdar
You might even consider 1.10.2 which seems to be the current stable release.Felix Kling
Is there a way to specify on your page the latest stable version of a jquery plugin so it automatically finds it?devdar
I am using 1.10.2 and still get this error. My setup is a bit different but the dialog is very much initialized when I call .dialog('close'), and the error still happens.Peter Herdenborg

20 Answers

22
votes

Looks like your buttons are not declared correctly (according to the latest jQuery UI documentation anyway).

try the following:

$( ".selector" ).dialog({ 
   buttons: [{ 
      text: "Ok", 
      click: function() { 
         $( this ).dialog( "close" ); 
      }
   }]
});
26
votes

I had a similar problem when opening a dialog with a partial layout in asp.net MVC. I was loading the jquery library on the partial page as well as the main page which was causing this error to come up.

16
votes

Try this - it works for me:

$(".editDialog").on("click", function (e) {
    var url = $(this).attr('href');
    $("#dialog-edit").dialog({
        title: 'Edit Office',
        autoOpen: false,
        resizable: false,
        height: 450,
        width: 380,
        show: { effect: 'drop', direction: "up" },
        modal: true,
        draggable: true,
        open: function (event, ui) {
            $(this).load(url);
        },
        close: function (event, ui) {
            $("#dialog-edit").dialog().dialog('close');
        }
    });

    $("#dialog-edit").dialog('open');
    return false;
});

Hope it will help you

10
votes

Im also got the same Error: cannot call methods on dialog prior to initialization; attempted to call method 'close'

what i did is i triggered the close button event which is in the dialog header like

this is working fine for me to close the dialog

function btnClose() {
$(".ui-dialog-titlebar-close").trigger('click');
}
9
votes

Is your $(this).dialog("close") by any chance being called from inside an Ajax "success" callback? If so, try adding context: this as one of the options to your $.ajax() call, like so:

$("#dialog").dialog({
    modal: true,
    buttons: {
        Ok: function() {
            $.ajax({
                url: '/path/to/request/url',
                context: this,
                success: function(data)
                {
                    /* Calls involving $(this) will now reference 
                       your "#dialog" element. */
                    $(this).dialog( "close" );
                }
            });
        }
    }
});
4
votes

it seems for some reason jQuery UI will try to run all code defined in buttons at definition time. It is crazy but I had the same issue and it stoped once I made this change.

if ($(this).dialog.isOpen === true) { 
    $(this).dialog("close");
}
3
votes

I got the same error in 1.10.2. In my case, I wanted to make clicking on the background overlay hide the currently visible dialog, regardless of which element it was based upon. Therefore I had this:

$('body').on("click", ".ui-widget-overlay", function () {
    $(".ui-dialog").dialog('destroy');
});

This used to be working, so I think they must have removed support in JQUI for calling .dialog() on the popup itself at some point.

My workaround looks like this:

$('body').on("click", ".ui-widget-overlay", function () {
    $('#' + $(".ui-dialog").attr('aria-describedby')).dialog('destroy');
});
2
votes

I had this problem once before where one dialog box was throwing this error, while all the others were working perfectly. The answer was because I had another element with the same id="dialogBox" else ware on the page. I found this thread during a search, so hopefully this will help someone else.

1
votes

I stumbled over the same and wanted to share my solution:

<script type="text/javascript">
    $( "#dialog-confirm" ).dialog("option","buttons",
                {
                    "delete": function() {
                        $.ajax({
                            url: "delete.php"
                        }).done(function(msg) {
                         //here "this" is the ajax object                                       
                            $(this).dialog( "close" );
                        });

                    },
                    "cancel": function() {
                        //here, "this" is correctly the dialog object
                        $(this).dialog( "close" );
                    }
                });
</script>

because "this" is referencing to an non-dialog object, I got the error mentioned.

Solution:

<script type="text/javascript">
    var theDialog = $( "#dialog-confirm" ).dialog("option","buttons",
                {
                    "delete": function() {
                        $.ajax({
                            url: "delete.php"
                        }).done(function(msg) {
                            $(theDialog).dialog( "close" );
                        });

                    },
                    "cancel": function() {
                        $(this).dialog( "close" );
                    }
                });
</script>
1
votes

So you use this:

var opt = {
        autoOpen: false,
        modal: true,
        width: 550,
        height:650,
        title: 'Details'
};

var theDialog = $("#divDialog").dialog(opt);
theDialog.dialog("open");

and if you open a MVC Partial View in Dialog, you can create in index a hidden button and JQUERY click event:

$("#YourButton").click(function()
{
   theDialog.dialog("open");
   OR
   theDialog.dialog("close");
});

then inside partial view html you call button trigger click like:

$("#YouButton").trigger("click")

see ya.

1
votes

This happened for me when my ajax was replacing contents on the page and ending up with two elements the same class for the dialog which meant when my line to close the dialog executed based on the CSS class selector, it found two elements not one and the second one had never been initialised.

$(".dialogClass").dialog("close"); //This line was expecting to find one element but found two where the second had not been initialised.

For anyone on ASP.NET MVC this occured because my controller action was returning a full view including the shared layout page which had the element when it should have been returning a partial view since the javascript was replacing only the main content area.

0
votes

After an hour ,i found best approach. we should save result of dialog in variable, after that call close method of variable.

Like this:

var dd= $("#divDialog")
.dialog({
   height: 600,
   width: 600,
   modal: true,
   draggable: false,
   resizable: false
});

// . . .

dd.dialog('close');
0
votes

I had a similar problem that I resolved by defining my button array outside of the dialog declaration.

var buttonArray = {};
buttonArray["Ok"] = function() { $( this ).dialog( "close" );}

Your options would become:

modal: true,
autoOpen: false,
buttons: buttonArray
0
votes

I was getting this error message when trying to close the dialog by using a button inside the dialog body. I tried to use $('#myDialog').dialog('close'); which did not work.

I ended up firing the click action of the 'x' button on the header using:

$('.modal-header:first').find('button:first').click();  
0
votes

Senguttuvan: your solution was the only thing that worked for me.

function btnClose() {
  $(".ui-dialog-titlebar-close").trigger('click');
}

0
votes

i have same problem, i open several dialog my problem was what the content should be removed to prevent the form data stay with same data, then the dialog is created these paramters

var dialog = $("#dummy-1");

    dialog.html('<div style="position:absolute; top:15px; left:0px; right:0px; bottom:0px; text-align:center;"><img align="middle" src="cargando.gif"></div>');
    dialog.html(mensaje);
    dialog.dialog(
    {
        title:'Ventana de Confirmacion',
        width:400, 
        height:200, 
        modal:true,
        resizable: false,
        draggable:false,
        position: { my: "center center", at: "center center", of: window },
        buttons:
        [
            {
                text: "Eliminar",
                click: function() {
                    functionCall(dialog,var1,var2);
                }
            },
            {
                text: "Cerrar",
                click: function() {
                    dialog.dialog("close");
                }
            }
        ],
        close: function(event, ui)
        {
            dialog.dialog("close").dialog("destroy").remove();
        }
    });

and the dialog is passed as a parameter to the function to do action:

    function functionCall(dialogFormulario,var1,var2)
{
    //same action 
        dialogFormulario.dialog("close");

}

Here it is necessary only to use .dialog("close") and no .dialog("destroy") because the dialog will call its function close: and the element will not exist

0
votes

I had a similar problem and in my case, the issue was different (I am using Django templates).

The order of JS was different (I know that's the first thing you check but I was almost sure that that was not the case, but it was). The js calling the dialog was called before jqueryUI library was called.

I am using Django, so was inheriting a template and using {{super.block}} to inherit code from the block as well to the template. I had to move {{super.block}} at the end of the block which solved the issue. The js calling the dialog was declared in the Media class in Django's admin.py. I spent more than an hour to figure it out. Hope this helps someone.

0
votes

Create a separate JavaScript function that can be called to close the dialog using the specific object id, and place the function outside of $(document).ready() like this:

function closeDialogWindow() { 
$('#dialogWindow').dialog('close');
}

NOTE: The function must be declared outside of $(document).ready() so jQuery doesn't try to trigger the close event on the dialog before it is created in the DOM.

0
votes

You may want to declare the button content outside of the dialog, this works for me.

var closeFunction = function() {
    $(#dialog).dialog( "close" );
};

$('#dialog').dialog({
    modal: true,
    buttons: {
        Ok: closeFunction
    }
});
0
votes

I know this is very old, but I got the same issue when I had to navigate through an angular route and the dialog is open, it remained open. So I got a workaround to call the close method in the route controller destructor. But got this above mentioned error if the dialog was not open. So the answer is if you are closing the dialog prior to initialization it will through this error. To check if the dialog is open then close it wrap your close state in this condition.

if($('#mydialog').dialog('isOpen')) { //close dialog code}