Search code examples
jquerybootstrap-modalstoppropagation

stopPropagation prevents bootstrap's dialog to be shown


I have a button inside a div

<div id="outerDiv">
    <button data-details-rid="@Model.RequestId" data-toggle="modal" data-target="#showRequestModal">Details</button>
</div>

A bootstrap's modal dialog

   <div id="showRequestModal" class="modal fade" role="dialog">
        <div class="modal-dialog">
            <!-- Modal content-->
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <div id="request-details-title">Details</div>
                </div>
                <div id="request-details-modal-body" class="modal-body">
                </div>
            </div>
        </div>
    </div>

and a jquery functions which run on-click event:

    $("[data-details-rid]").on('click', function (event) {
        var request_id = $(this).attr('data-details-rid');
        console.log(request_id);
        var request_details = {};
        request_details.url = "/Requests/Details?RequestId=" + request_id;
        request_details.async = false;
        request_details.datatype = "html";
        request_details.contentType = "application/json; charset=utf-8";
        request_details.success = function (request_info) {/*...*/};
        $.ajax(request_details);
    });

$("#outerDiv").on('click', function (event) {
    another ajax call
});

now, obviously, when I click the button the the #outerDiv function is called too (undesirable affect).

when I put event.stopPropagation() like this:

$("[data-details-rid]").on('click', function (event) {
    event.stopPropagation();
    var request_id = $(this).attr('data-details-rid');
    console.log(request_id);
    var request_details = {};
    request_details.url = "/Requests/Details?RequestId=" + request_id;
    request_details.async = false;
    request_details.datatype = "html";
    request_details.contentType = "application/json; charset=utf-8";
    request_details.success = function (request_info) {/*...*/};
    $.ajax(request_details);
});

then the modal dialogue does not appear. why?


Solution

  • That's the expected behavior. By using stopPropagation you are basically saying that no more click event handlers will be notified of that event like you can read in the documentation. You can however trigger the modal manually using: $("#showRequestModal").modal('show');