Close dynamically created jQuery-ui dialog

I am creating a user information editing dialog box that retrieves the editing information using $.post , but I cannot close this dialog because the dialog was not initialized using any HTML element.

I am trying $('#editUser').dialog('close') but this will not work.

Here is the main object:

 <div id='userInfo'> <div class='user'> <span class='userId'>1</span> <span class='userName'>John</span> </div> <div class='user'> <span class='userId'>2</span> <span class='userName'>Jane</span> </div> 

and here is the script used to create the dialog:

 $(function() { $('.user').click(function() { var uid = $(this).find('span.userId').html(); $post('/e-val/user/edit.php', {id: uid}, function(html) { $(html).dialog(); }); }); $('body').on('click', '#closeEditDialog', function() { $('#editUser').dialog('close') }); }); 

The dialog opens as expected, but does not close as it should.

This is the HTML for the dialog returned by the ajax script.

 <div id='editUser'> <table> <tr> <td>Username</td> <td><?php echo $user['name'] ?></td> </tr> <tr> <td>Email</td> <td><?php echo $user['email'] ?></td> </tr> <tr> <td colspan='2'> <input type='button' id='closeEditDialog' value='close' /> </td> </tr> </table> </div> 

What can I do to close it? I can use $('#editUser').remove() Remove $('#editUser').remove() to remove the dialog, but I need to close it so as not to remove it.

+4
source share
3 answers

$('#editUser').dialog('close') will not work because you never used $('#editUser') to initialize the dialog , so you cannot use it to close it. You need to use the same handler that was used to create it.

As Gil and Trin answered here: Just first add the contents of the dialog box to the DOM, and then initialize the dialog:

 $post('/e-val/user/edit.php', {id: uid}, function(html) { $(html).appendTo('body'); $('#editUser').dialog( {autoOpen: false} ); }); 

autoOpen: false prevent the dialog from opening by itself and it can be opened with $('#editUser').dialog('open') at any time.

+1
source
 var mydialog; $(function() { $('.user').click(function() { var uid = $(this).find('span.userId').html(); $post('/e-val/user/edit.php', {id: uid}, function(html) { mydialog = $(html); mydialog.appendTo('body'); mydialog.dialog(); }); }); $('body').on('click', '#closeEditDialog', function() { mydialog.dialog('close') }); }); 
+2
source

You may need to insert this html in the DOM before creating a dialog.

 $("body").append(html); $("#editUser").dialog(); 

Well, at least if your dialog appears in this way, nothing interferes with closing, you use the same selector.

EDIT

Also, do not forget that .dialog () initializes the widget; try not to call it more than once. Use .dialog ("open") instead.

It would be best to add the div dialog to your html and then add your server-side code to it to dynamically update the contents of the dialog box.

+2
source

All Articles