Twitter bootstrap remote modal shows same content every time

JqueryJquery PluginsTwitter BootstrapModal Dialog

Jquery Problem Overview


I am using Twitter bootstrap, I have specified a modal

<div class="modal hide" id="modal-item">

    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">x</button>
        <h3>Update Item</h3>
    </div>

	<form action="http://www.website.com/update" method="POST" class="form-horizontal">

    <div class="modal-body">
    	Loading content...
    </div>

    <div class="modal-footer">
        <a href="#" class="btn" data-dismiss="modal">Close</a>
        <button class="btn btn-primary" type="submit">Update Item</button>
    </div>

	</form>

</div>

And the links

<a href="http://www.website.com/item/1" data-target="#modal-item" data-toggle="modal">Edit 1</a>
<a href="http://www.website.com/item/2" data-target="#modal-item" data-toggle="modal">Edit 2</a>
<a href="http://www.website.com/item/3" data-target="#modal-item" data-toggle="modal">Edit 2</a>

When I click on any of these link for the first time, I see the correct content, but when I click on other links it shows the same content loaded for the first time, it doesn't update the content.

I want it to be updated every time its clicked.

P.S : I can easily make it work via custom jQuery function, but I want to know if it's possible with native Bootstrap modal remote function, as it should be easy enough and I guess I am just complicating things.

Jquery Solutions


Solution 1 - Jquery

The problem is two-fold.

First, once a Modal object is instantiated, it is persistently attached to the element specified by data-target and subsequent calls to show that modal will only call toggle() on it, but will not update the values in the options. So, even though the href attributes are different on your different links, when the modal is toggled, the value for remote is not getting updated. For most options, one can get around this by directly editing the object. For instance:

$('#myModal').data('bs.modal').options.remote = "http://website.com/item/7";
However, that won't work in this case, because...

Second, the Modal plugin is designed to load the remote resource in the constructor of the Modal object, which unfortunately means that even if a change is made to the options.remote, it will never be reloaded.

A simple remedy is to destroy the Modal object before subsequent toggles. One option is to just destroy it after it finishes hiding:

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

Note: Adjust the selectors as needed. This is the most general.

Plunker

Or you could try coming up with a more complicated scheme to do something like check whether the link launching the modal is different from the previous one. If it is, destroy; if it isn't, then no need to reload.

Solution 2 - Jquery

For bootstrap 3 you should use:

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

Solution 3 - Jquery

For Bootstrap 3.1 you'll want to remove data and empty the modal-content rather than the whole dialog (3.0) to avoid the flicker while waiting for remote content to load.

$(document).on("hidden.bs.modal", function (e) {
	$(e.target).removeData("bs.modal").find(".modal-content").empty();
});

If you are using non-remote modals then the above code will, of course, remove their content once closed (bad). You may need to add something to those modals (like a .local-modal class) so they aren't affected. Then modify the above code to:

$(document).on("hidden.bs.modal", ".modal:not(.local-modal)", function (e) {
	$(e.target).removeData("bs.modal").find(".modal-content").empty();
});

Solution 4 - Jquery

Thanks merv. I started tinkering around boostrap.js but your answer is a quick and clean workaround. Here's what I ended up using in my code.

$('#modal-item').on('hidden', function() {
	$(this).removeData('modal');
});

Solution 5 - Jquery

The accepted answer didn't work for me, so I went with JavaScript to do it.

<a href="/foo" class="modal-link">
<a href="/bar" class="modal-link">

<script>
$(function() {
    $(".modal-link").click(function(event) {
        event.preventDefault()
        $('#myModal').removeData("modal")
        $('#myModal').modal({remote: $(this).attr("href")})
    })
})

Solution 6 - Jquery

This works with Bootstrap 3 FYI

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

Solution 7 - Jquery

My project is built in Yii & uses the Bootstrap-Yii plugin, so this answer is only relevant if you're using Yii.

The above fix did work but only after the first time the modal was shown. The first time it came up empty. I think that's because after my initiation of the code Yii calls the hide function of the modal thereby clearing out my initiation variables.

I found that putting the removeData call immediately before the code that launched the modal did the trick. So my code is structured like this...

$ ("#myModal").removeData ('modal');
$ ('#myModal').modal ({remote : 'path_to_remote'});

Solution 8 - Jquery

In Bootstrap 3.2.0 the "on" event has to be on the document and you have to empty the modal :

$(document).on("hidden.bs.modal", function (e) {
    $(e.target).removeData("bs.modal").find(".modal-content").empty();
});

In Bootstrap 3.1.0 the "on" event can be on the body :

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

Solution 9 - Jquery

Why not make it more general with BS 3? Just use "[something]modal" as the ID of the modal DIV.

$("div[id$='modal']").on('hidden.bs.modal',
    function () {
        $(this).removeData('bs.modal');
    }
);

Solution 10 - Jquery

Only working option for me is:

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

I use Bootstrap 3 and I have a function called popup('popup content') which appends the modal box html.

Solution 11 - Jquery

Adding an $(this).html(''); to clear visible data as well, and it works pretty fine

Solution 12 - Jquery

If a remote URL is provided, content will be loaded one time via jQuery's load method and injected into the .modal-content div. If you're using the data-api, you may alternatively use the href attribute to specify the remote source. An example of this is shown below

$.ajaxSetup ({
    // Disable caching of AJAX responses
    cache: false
});

Solution 13 - Jquery

I've added something like this, because the older content is shown until the new one appears, with .html('') inside the .modal-content will clear the HTML inside, hope it helps

$('#myModal').on('hidden.bs.modal', function () {
   $('#myModal').removeData('bs.modal');
   $('#myModal').find('.modal-content').html('');
});

Solution 14 - Jquery

I wrote a simple snippet handling the refreshing of the modal. Basically it stores the clicked link in the modal's data and check if it's the same link that has been clicked, removing or not the modal data.

var handleModal = function()
{
    $('.triggeringLink').click(function(event) {
        var $logsModal = $('#logsModal');
        var $triggeringLink = $logsModal.data('triggeringLink');

        event.preventDefault();

        if ($logsModal.data('modal') != undefined
            && $triggeringLink != undefined
            && !$triggeringLink.is($(this))
        ) {
            $logsModal.removeData('modal');
        }

        $logsModal.data('triggeringLink', $(this));

        $logsModal.modal({ remote: $(this).attr('href') });
        $logsModal.modal('show');
    });
};

Solution 15 - Jquery

For Bootstrap 3, in modal.js I changed:

$(document)
  .on('show.bs.modal',  '.modal', function () { $(document.body).addClass('modal-open') })
  .on('hidden.bs.modal', '.modal', function () { $(document.body).removeClass('modal-open'); })

to

$(document)
  .on('show.bs.modal',  '.modal', function () { $(document.body).addClass('modal-open') })
  .on('hidden.bs.modal', '.modal', function () { 
    $(this).removeData('bs.modal').empty()
    $(document.body).removeClass('modal-open')
  })

(extra spacing added for clarity)

This prevents any unwanted flash of old modal content by calling empty() on the modal container as well as removing the data.

Solution 16 - Jquery

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

This one works for me.

Solution 17 - Jquery

This other approach works well for me:

$("#myModal").on("show.bs.modal", function(e) {
    var link = $(e.relatedTarget);
    $(this).find(".modal-body").load(link.attr("href"));
});

Solution 18 - Jquery

$('body').on('hidden.bs.modal', '.modal', function () {
	   $("#mention Id here what you showed inside modal body").empty()
});

Which html element you want to empty like(div,span whatever).

Solution 19 - Jquery

This one works for me:

modal

<div class="modal fade" id="searchKaryawan" tabindex="-1" role="dialog" aria-labelledby="SearchKaryawanLabel" aria-hidden="true"> <div class="modal-dialog">
<div class="modal-content">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
    <h4 class="modal-title" id="SearchKaryawanLabel">Cari Karyawan</h4>
  </div>
  <div class="modal-body">
    <input type="hidden" name="location">
    <input name="cariNama" type="text" class="form-control" onkeyup="if (this.value.length > 3) cariNikNama();" />
    <div class="links-area" id="links-area"></div>
  </div>
  <div class="modal-footer">
  </div>
</div> </div></div>

script

<script type="text/javascript">$('body').on('hidden.bs.modal', '.modal', function () {  $(".links-area").empty() }); </script>

links-area is area where i put the data and need to clear

Solution 20 - Jquery

Expanded version of accepted answer by @merv. It also checks if modal being hidden is loaded from remote source and clears old content to prevent it from flashing.

$(document).on('hidden.bs.modal', '.modal', function () {
  var modalData = $(this).data('bs.modal');
  
  // Destroy modal if has remote source – don't want to destroy modals with static content.
  if (modalData && modalData.options.remote) {
    // Destroy component. Next time new component is created and loads fresh content
    $(this).removeData('bs.modal');
    // Also clear loaded content, otherwise it would flash before new one is loaded.
    $(this).find(".modal-content").empty();
  }
});

https://gist.github.com/WojtekKruszewski/ae86d7fb59879715ae1e6dd623f743c5

Solution 21 - Jquery

Tested on Bootstrap version 3.3.2

  $('#myModal').on('hide.bs.modal', function() {
    $(this).removeData();
  });

Solution 22 - Jquery

Good luck with this one:

$('#myModal').on('hidden.bs.modal', function () {
    location.reload();
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDhruv Kumar JhaView Question on Stackoverflow
Solution 1 - JquerymervView Answer on Stackoverflow
Solution 2 - JqueryCamilo NovaView Answer on Stackoverflow
Solution 3 - JqueryslopapaView Answer on Stackoverflow
Solution 4 - JqueryBienvenido DavidView Answer on Stackoverflow
Solution 5 - JqueryJames WardView Answer on Stackoverflow
Solution 6 - JqueryDave SagView Answer on Stackoverflow
Solution 7 - JquerySean ToruView Answer on Stackoverflow
Solution 8 - JqueryRomainView Answer on Stackoverflow
Solution 9 - Jqueryuser2763645View Answer on Stackoverflow
Solution 10 - JqueryOrkun TuzelView Answer on Stackoverflow
Solution 11 - JquerywebstrView Answer on Stackoverflow
Solution 12 - JqueryCiprian MihalacheView Answer on Stackoverflow
Solution 13 - JqueryMau GMView Answer on Stackoverflow
Solution 14 - JqueryDevAntoineView Answer on Stackoverflow
Solution 15 - JqueryStantonView Answer on Stackoverflow
Solution 16 - JqueryShawn AngView Answer on Stackoverflow
Solution 17 - JqueryRhys StephensView Answer on Stackoverflow
Solution 18 - JqueryAtulView Answer on Stackoverflow
Solution 19 - JquerydewazView Answer on Stackoverflow
Solution 20 - JqueryWojtek KruszewskiView Answer on Stackoverflow
Solution 21 - JqueryAbudayahView Answer on Stackoverflow
Solution 22 - JqueryMappyView Answer on Stackoverflow