How do I close a dialog using jQuery?

Shahin picture Shahin · Jun 15, 2011 · Viewed 30.5k times · Source

I am using the code below to create a jQuery UI Dialog widget dynamically:

 $(function () {
        var Selector = $("a:contains('sometext')");
        $(Selector).bind('click', function () {
            var NewDialog = "<div dir=rtl id='MenuDialog'></div>";
            var DialogContetn = '<div dir=rtl ><table width=100%><tr><td><textarea id="txtRequestContent" cols="30" rows="2"></textarea></td><td><table><tr><td><input id="btnSendEditionRequest" type="button" value="Send" /></td></tr><tr><td><input id="btnCloseDialog" type="button" value="Cancel" /></td></tr></table></td></tr></table></div>';
            $('body').append(NewDialog);
            $('#MenuDialog').html(DialogContetn);
            $('#MenuDialog').hide();
            $('#MenuDialog').dialog({ modal: true, title: "title", show: 'clip', hide: 'clip' });
            $("#btnCloseDialog").live('click', function () {
                $("#MenuDialog").dialog('close');
            });
            return false;
        });
    });

First time it loads, the jQuery Dialog works correctly and when I click on the btnCloseDialog the jQuery Dialog closes successfully.

However, after that, the btnCloseDialog no longer closes the dialog. Why is this happening?

Update

I put my code out on a jsfiddle.

This is strange behavior because the button closes the dialog properly in the jsFiddle, but not on the dialog in my project.

Answer

&#201;velyne Lachance picture Évelyne Lachance · Oct 25, 2011

Because this shows up early in the search for creating a dynamic dialog in jquery, I'd like to point out a better method to do this. Instead of adding your dialog div and content to the HTML and then calling it, you can do this much more easily by shoving the HTML directly into a jquery object, as so:

$(function () {
    $("a:contains('sometext')").click(function() {
        var NewDialog = $('<div id="MenuDialog">\
            <p>This is your dialog content, which can be multiline and dynamic.</p>\
        </div>');
        NewDialog.dialog({
            modal: true,
            title: "title",
            show: 'clip',
            hide: 'clip',
            buttons: [
                {text: "Submit", click: function() {doSomething()}},
                {text: "Cancel", click: function() {$(this).dialog("close")}}
            ]
        });
        return false;
    });
});

I've also showed how you can put multiple buttons with inline functions, instead of attaching a live() function to the button. I've used this method in a couple of places and it works great for me. It also supports forms (I grabbed the data in doSomething() and submitted through ajax, but other methods work too), etc.