user1996496 user1996496 - 3 months ago 16
Javascript Question

How do I clear Bootstrap remote modal content on close?

I am launching a modal with remote content (on the same domain, however). The modal can be opened several times with different content on the same page, so when it closes, I need it to

clear
the
.modal-body
part.

I tried to do it like this:

function close_modal()

{

$('.modal').modal('hide');

$('body').on('hidden.bs.modal', '.modal', function () {
$(this).removeData('bs.modal');
});


}


But for some reason the previous content is still visible for a split second when I open another modal target. I also checked the source code and the content loaded previously is still there. How do I fix this? Here is my markup:

$('a[rel=modal]').on('click', function(evt) {
evt.preventDefault();
var modal = $('#modal').modal();
modal
.find('.modal-body')
.load($(this).attr('href'), function (responseText, textStatus) {
if ( textStatus === 'success' ||
textStatus === 'notmodified')
{
modal.show();
}
});
});


and the HTML:

<div id="modal" class="modal fade"
tabindex="-1" role="dialog" aria-labelledby="plan-info" aria-hidden="true">
<div class="modal-dialog modal-full-screen">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close"
data-dismiss="modal" aria-hidden="true">
<span class="glyphicon glyphicon-remove-circle"></span>
</button>
</div>
<div class="modal-body">
<!-- /# content goes here -->
</div>
</div>
</div>
</div>

Answer

You should be able to use jQuery's empty method to remove all child nodes from .modal-body:

$('body').on('hidden.bs.modal', '.modal', function () {
    $(this).find('.modal-body').empty();
});