Karl Kieninger
Karl Kieninger

Reputation: 9129

jQueryUI Dialog Does Not Close

I think I'm doing this right, but neither button actually closes. Either I'm blind or missing a subtlety.

jsFiddle

HTML

<div id="sample-dialog" title="New Effect"></div>
<button>Button</button>

JS

$(document).ready(function () {
    $(function () {

        $(function () {
            $("button")
                .button()
                .click(function (event) {
                event.preventDefault();
                $("#sample-dialog").dialog("open");
            });
        });

        $("#sample-dialog").dialog({
            autoOpen: false,
            height: 200,
            width: 200,
            modal: true,
            buttons: {
                "Close by $(#id)": function () {
                    $("#sample-dialog").dialog("close");
                },
                    "Close by $(this)": function () {
                    $(this).dialog("close");
                }
            }
        });

    });

});

I started the process trying to follow and modify this sample.

Upvotes: 1

Views: 2646

Answers (1)

Jason P
Jason P

Reputation: 27012

Apparently wrapping the button click handler in $(function() {...}) causes that to be executed after the function to create the dialog. The buttons in the dialog are, well, <button>s, so clicking them closes the dialog, but the click handler immediately reopens the dialog. It works without the extra $(function() {...}), which shouldn't be necessary anyway:

http://jsfiddle.net/nLvwp/

$(document).ready(function () {
    $("button")
        .button()
        .click(function (event) {
        event.preventDefault();
        $("#sample-dialog").dialog("open");
    });

    $("#sample-dialog").dialog({
        autoOpen: false,
        height: 200,
        width: 200,
        modal: true,
        buttons: {
            "Close by $(#id)": function () {
                $("#sample-dialog").dialog("close");
            },
                "Close by $(this)": function () {
                $(this).dialog("close");
            }
        }
    });
});

You could also solve the problem by being more specific in selecting the button that should open the dialog. But a single $(document).ready(function{...}) or $(function() {...}) (which do the same thing) is sufficient.

Upvotes: 2

Related Questions