Close a Jquery modal using load()

I've made a modal dialog used load() method but now I don't know how to close it.

The button and div:

<a href="#" id="btnAdd">Add</a>

<div id="AddModal" style="display:none"></div>

Script to call the modal:

$("#btnAdd").click(function () {
    $("#AddModal").load("/Customer/Modal/AddCustomerModal.aspx").show();
});

AddCustomerModal loaded inside the AddModal:

<body>
    <div id="AddModalContent">
        <h3>MODAL</h3>

        XYZ<br />
        <input type="button" class="btnCloseModal" value="Close" />
    </div>
</body>

Script to close

$(".btnCloseModal").click(function () {
        $("#AddModal").hide();
});

Answers 1

  • Your problem is that the .btnCloseModal doesn't exist before you load it's content into your page, so you can't really attach the click event to this element (yet).

    The solution is to attach the click event to the #AddModal element, and check for the .btnCloseModal element inside:

    $("#AddModal").on('click', '.btnCloseModal', function () {
        $("#AddModal").hide();
    });
    

Related Articles