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

JavascriptJqueryHtmlJquery Ui

Javascript Problem Overview


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>

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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

Solution 3 - Javascript

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

Solution 4 - Javascript

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

Solution 5 - Javascript

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

Solution 6 - Javascript

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

Solution 7 - Javascript

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

Solution 8 - Javascript

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.

Solution 9 - Javascript

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>

Solution 10 - Javascript

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.

Solution 11 - Javascript

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.

Solution 12 - Javascript

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

Solution 13 - Javascript

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

Solution 14 - Javascript

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

Solution 15 - Javascript

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

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

Solution 16 - Javascript

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

Solution 17 - Javascript

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.

Solution 18 - Javascript

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.

Solution 19 - Javascript

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

Solution 20 - Javascript

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}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondevdarView Question on Stackoverflow
Solution 1 - JavascriptBehrView Answer on Stackoverflow
Solution 2 - JavascriptpmckeownView Answer on Stackoverflow
Solution 3 - JavascriptEdsonFView Answer on Stackoverflow
Solution 4 - JavascriptSenguttuvan AmaladassView Answer on Stackoverflow
Solution 5 - JavascriptAdrian LopezView Answer on Stackoverflow
Solution 6 - JavascriptJohnPanView Answer on Stackoverflow
Solution 7 - JavascriptPeter HerdenborgView Answer on Stackoverflow
Solution 8 - JavascriptAndrew FoxView Answer on Stackoverflow
Solution 9 - JavascriptoshView Answer on Stackoverflow
Solution 10 - JavascriptDanilo AntoniettoView Answer on Stackoverflow
Solution 11 - JavascriptAlan MacdonaldView Answer on Stackoverflow
Solution 12 - JavascriptsteadView Answer on Stackoverflow
Solution 13 - JavascriptHamed KhatamiView Answer on Stackoverflow
Solution 14 - JavascriptCrackerjackView Answer on Stackoverflow
Solution 15 - Javascriptuser1229595View Answer on Stackoverflow
Solution 16 - JavascriptKristKingView Answer on Stackoverflow
Solution 17 - JavascriptAnupamView Answer on Stackoverflow
Solution 18 - JavascriptJohn VercoView Answer on Stackoverflow
Solution 19 - JavascriptjpotterhView Answer on Stackoverflow
Solution 20 - JavascriptSahib KhanView Answer on Stackoverflow