Reputation: 10681
I'm using Bootstrap (Version 2.3.1) and I'm using Ajax to load in a modal window. Is there a way to remove the modal window from the DOM when I close the modal window?
$('[data-toggle="modal"]').click(function(e) {
e.preventDefault();
var url = $(this).attr('href');
if (url.indexOf('#') == 0) {
$(url).modal('open');
} else {
$.get(url, function(data) {
$(data).modal();
}).success(function() {
console.log('success');
// I tried this below but didn't work
// $('#modalClose).on('click',function(){
// $('#myModalWindow').remove();
// });
});
}
});
My button:
<a href="path/to/modal.html" data-target="#" data-toggle="modal">Launch modal</a>
In my modal window, I have a close button.
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
However, when I close the modal, the html is still in the DOM and if I load the modal again, it outputs the HTML again. Is there a way to remove the modal window from the DOM when I close the modal window?
Upvotes: 0
Views: 3459
Reputation: 5564
Additional css classes associated with a Bootstrap modal need to be removed.
Try putting this in success:
$('body').on('click', '#btn-close-modal', function () {
$('#my-modal').modal('hide');
$('body').removeClass('modal-open');
$('.modal-backdrop').remove();
});
Where btn-close-modal
is some button you use to remove the modal and my-modal
is the name of the modal in question.
Upvotes: 1
Reputation: 16359
Should be pretty straightforward using .remove():
<button id="ModalClose" class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
$('#ModalClose').on('click',function(){
$('#IdOfModal').remove();
});
This should remove the full modal HTML from the DOM. Just note I gave the close button an id, and use that id as click reference.
If your modal (and therefore close button) is loaded through AJAX, then the dynamically-loaded elements will only be able to have any Javascript/jQuery work with them if applied in a callback function for that modal's load.
Upvotes: 0