[javascript] JQuery Error: cannot call methods on dialog prior to initialization; attempted to call method 'close'

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>

This question is related to javascript jquery html jquery-ui

The answer is


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.


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");
}

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

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


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}

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.


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


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
    }
});

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.


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');
});

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


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.


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');

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

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" );
                }
            });
        }
    }
});

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();  

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>

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');
}

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.


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.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to jquery-ui

How to auto adjust the div size for all mobile / tablet display formats? jQuery not working with IE 11 JavaScript Uncaught ReferenceError: jQuery is not defined; Uncaught ReferenceError: $ is not defined Best Practice to Organize Javascript Library & CSS Folder Structure Change table header color using bootstrap How to get HTML 5 input type="date" working in Firefox and/or IE 10 Form Submit jQuery does not work Disable future dates after today in Jquery Ui Datepicker How to Set Active Tab in jQuery Ui How to use source: function()... and AJAX in JQuery UI autocomplete