Search code examples
jqueryjquery-pluginstwitter-bootstrapmodal-dialog

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.example/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.example/item/1" data-target="#modal-item" data-toggle="modal">Edit 1</a>
<a href="http://www.website.example/item/2" data-target="#modal-item" data-toggle="modal">Edit 2</a>
<a href="http://www.website.example/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.


Solution

  • 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.example/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.