[jquery] Twitter bootstrap remote modal shows same content every time

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.

This question is related to jquery jquery-plugins twitter-bootstrap modal-dialog

The answer is


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');
    }
);

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'});

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');
});

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('');
});

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.


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
});

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');
    });
};

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


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');
});

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.


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")})
    })
})

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

This one works for me.


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();
});

Good luck with this one:

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

This works with Bootstrap 3 FYI

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

For bootstrap 3 you should use:

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

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"));
});

$('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).


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


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


Tested on Bootstrap version 3.3.2

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

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to jquery-plugins

How to use a jQuery plugin inside Vue How add spaces between Slick carousel item Bootstrap carousel multiple frames at once Can someone explain how to implement the jQuery File Upload plugin? Correct way to integrate jQuery plugins in AngularJS Call Jquery function Twitter bootstrap remote modal shows same content every time Jquery Chosen plugin - dynamically populate list by Ajax How to show all rows by default in JQuery DataTable Change Placeholder Text using jQuery

Examples related to twitter-bootstrap

Bootstrap 4: responsive sidebar menu to top navbar CSS class for pointer cursor How to install popper.js with Bootstrap 4? Change arrow colors in Bootstraps carousel Search input with an icon Bootstrap 4 bootstrap 4 responsive utilities visible / hidden xs sm lg not working bootstrap.min.js:6 Uncaught Error: Bootstrap dropdown require Popper.js Bootstrap 4 - Inline List? Bootstrap 4, how to make a col have a height of 100%? Bootstrap 4: Multilevel Dropdown Inside Navigation Read input from a JOptionPane.showInputDialog box Disable click outside of angular material dialog area to close the dialog (With Angular Version 4.0+) How can I display a modal dialog in Redux that performs asynchronous actions? Angular 2.0 and Modal Dialog How to use Bootstrap modal using the anchor tag for Register? Bootstrap modal opening on page load Trying to make bootstrap modal wider How to present a modal atop the current view in Swift Send parameter to Bootstrap modal window? Set bootstrap modal body height by percentage