views:

274

answers:

2

When an ajax operation fails, I create a new div with the errors and then show it as a dialog. When the dialog is closed I would like to completely destroy and remove the div again. How can I do this? My code looks something like this at the moment:

$('<div>We failed</div>')
    .dialog(
    {
        title: 'Error',
        close: function(event, ui)
        {
            $(this).destroy().remove();
        }
    });

When I run this the dialog box shows up correctly, but when I close it the dialog is still visible in the html (using FireBug). What am I missing here? Something I have forgotten?

Update: Just noticed my code gives me an error in the firebug console.

$(this).destroy is not a function

Anyone able to help me out?

Update: If I do just $(this).remove() instead, the item is removed from the html. But is it completely removed from the DOM? Or do I somehow need to call that destroy function first as well?

+1  A: 
$(this).dialog('destroy').remove()

This will destroy the dialog and then remove the div that was "hosting" the dialog completely from the DOM

lomaxx
Oooooh. Right... *facepalm* Thank you!!
Svish
A: 

Why do you want it removing?

If it is to prevent multiple instances being created, then just use the following approach...

$('#myDialog') 
    .dialog( 
    { 
        title: 'Error', 
        close: function(event, ui) 
        { 
            $(this).dialog('close');
        } 
    }); 

And when the error occurs, you would do...

$('#myDialog').html("Ooops.");
$('#myDialog').dialog('open');
Fiona Holder
I just thought it would be easier, since it will contain different content depending on what I get back from an ajax call. And also the div isn't static like I showed in my example but rendered by the http://github.com/nje/jquery-tmpl plugin. If you have a good way of swapping out the contents of the dialog I would be interested in seeing that though :)
Svish
Well, in my example, I went with the extremely simple option of just dumping a string withing the dialog div: $('#myDialog').html("Ooops.");You could modify this to change the content of any sub-controls in the dialog div as well.
Fiona Holder