On my web page I am loading an editing form asyncronously with jQuery.get and showing it inside of jQuery dialog. For some reason, multiple instances of the div that I am aplying .dialog on are being appended to document.body. Here is my loading code:
function openEditProjectDialog(event) {
var projectNameToEdit = $(event.currentTarget).closest('.project-item').find('.project-name').text();
var url = $("#EditProjectActionUrl").val();
var dataString = 'name=' + projectNameToEdit + '&__RequestVerificationToken=' + encodeURIComponent($("input[name=__RequestVerificationToken]").val());
$.get(url, dataString)
.done(function (content) {
$('.modal-popup').remove();
var popupDiv = $('<div class="modal-popup"><div id="edit-project-block">' + content + '</div></div>').hide();
var whatWeDialogOn = popupDiv.appendTo(document.body);
whatWeDialogOn.dialog({
title: 'Editing project <b>' + projectNameToEdit + '</b>',
modal: true,
resizable: false,
draggable: true,
width: 725,
close: function(event, ui) {
$(this).dialog('destroy').remove();
$('.modal-popup').remove();
}
});
$("#edit-project-block #bottomAreaHtml").attr("id", "bottomAreaHtmlToEdit");
CKEDITOR.replace('bottomAreaHtmlToEdit');
$('.chzn-select').chosen();
$("#edit-project-block #submit-project").on("click", submitUpdatedProject);
});
}
$('#projects').on("click", '.edit-project', openEditProjectDialog);
At this point:
.done(function (content) {
$('.modal-popup').remove();
there are two <div class="modal-popup" style="display:none"> already appended to a document. After .remove call there is one left. (I know there should be none =) After the .dialog is called, there are 6 or 7 modal-popup divs and the only one inside the jQuery UI div that is actually displayed.
If what I am describing sounds rediculouse – let me know. What may be the source of the problem?
P.S. var popupDiv = $('<div class="modal-popup">... is the only spot where div with such name gets added to the DOM.
Try structuring the function to account for variable declaration hoisting and do your removals before additions (like so):