ducin
ducin

Reputation: 26477

jqueryUI: initialising dialog content on first click

This should be easy for experienced jqueryUI users. What I'd like to achieve is:

At the moment I've got most of those, but using two distinct jquery UI buttons. I'm using icanhaz, but it should make no difference, since I got this part working fine. This is the html part:

<script id="user" type="text/html">
    <p>
        There are following users:
        <ul>
        {{#users}}
            <input type="checkbox" name="user" value="{{ username }}" />{{ fullname }}
            {{^last}}<br />{{/last}}
        {{/users}}
        </ul>
    </p>
</script>

<a id="user-btn" class="btn">show users</a>

<a id="dialog-btn" class="btn">show dialog</a>

<div id="dialog-message" title="Select users">
</div>

and this is javascript part:

$(document).ready( function() {

    $("#user-btn").click(function() {
        $.ajax({
            type: "GET",
            dataType: "json",
            url: "../php/client/json.php",
            data: {
                type: "users"
            }
        }).done(function( response ) {
            var element = $('#dialog-message');
            element.append(ich.user(response));
        });
    });

    $("#dialog-btn").click(function() {
        $("#dialog-message").dialog().dialog("open");
    });
});

When I click the first button, "show users", it generates the content for the dialog. When I click "show dialog", the dialog is created and opened. I'd jut like to clean it - to call the ajax (and render icanhaz) when clicked, use the rendered html to create the dialog, open the dialog and display (all in one single click).

Upvotes: 0

Views: 122

Answers (1)

tcovo
tcovo

Reputation: 7770

$(document).ready( function() {

    $("#user-btn").click(function() {
        if ($('#dialog-message').is('.ui-dialog-content')) {
            // data already loaded and dialog already initialized
            $('#dialog-message').dialog('open');
        } else {
            // request data and initialize dialog
            $.ajax({
                type: "GET",
                dataType: "json",
                url: "../php/client/json.php",
                data: {
                    type: "users"
                }
            }).done(function( response ) {
                $('#dialog-message')
                    .append(ich.user(response)) // load data into element
                    .dialog(); // show as dialog (autoOpen is true by default)
            });
        }
    });
});

$('#dialog-message').is('.ui-dialog-content') is just one way to check if a dialog has already been initialized on an element; there may be a better way.

Upvotes: 1

Related Questions