Search code examples
javascriptjquerydjangobootstrap-modal

Close Bootstrap Modal from within injected HTML?


Script to Call Modal, and HTML Skeleton for Modal: (which is working)

<script>
$(document).on("click", ".addworker", function (e) {
    e.preventDefault();
    var $popup = $("#popup");
    var popup_url = $(this).data("popup-url");
    $(".modal-content", $popup).load(popup_url, function () {
        $popup.modal("show");
    });
});
</script>

<div id="popup" class="modal fade" role="dialog">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
        
        </div>
    </div>
</div>

The HTML loaded into modal-content is returned by a django view which sits behind the url. (this part is working too)

Inside this HTML i have the Button, which i want to use to then close the modal again. But when the Modal got injected with the HTML and is open, it seems like the modal is out of scope, so i tried to get it back with var $popup = $("#popup");. And i indeed get back the Object, but the $popup.modal("hide"); Method doesnt work.

<script>
    $(document).on("click", ".cancel", function (e) {
        var $popup = $("#popup");
        $popup.modal("hide");
    });
</script>

<div class="modal-header">
<h1>{{ aoe }} Worker: {{ id }}</h1>
</div>
<form action="add/" method="post">
    {% csrf_token %}
    <div class="modal-body">
    {{ form|crispy }}
    </div>
    <div class="modal-footer">
    <input type="button" class="btn btn-secondary cancel" value="Cancel">
    <input type="submit" class="btn btn-primary" value="Submit">
    </div>
</form>

My first workaround: (inside the html file that gets injected to the modal)

<script>
    $(document).on("click", ".cancel", function (e) {
        var $popup = document.querySelector('#popup');
        $popup.classList.remove('show');
        $('#popup').css("display", "none");
        var $back = document.querySelector('.modal-backdrop');
        $back.parentNode.removeChild($back);
    });
</script>

This works, but is not really that convenient.

Second Workaround: Just call $("#popup").click() when pressing the Close Button, to simulate a click into the free area next to the Modal. Feels like cheating, but at least its less effort now.

Still, i would like to know the "proper" way to do this.


Solution

  • Problem Solved. I included JQuery in Both HTML Files, which seemed to cause the function not to work anymore. Now it works using $("#popup").modal('hide');