Search code examples
javascripttwitter-bootstrap-3modal-dialogdismiss

How to detect the dismissal of a bootstrap modal dialog in javascript?


I am trying to work with the bootstrap modal dialog. The events I am using are hidden and show. I have no problem using the show event. I don't understand how to use the hidden event on the other hand. I am displaying a form in the modal dialog and on the submit event of the form, I am hiding the modal dialog with $('.modal').modal('hide'). This hide event is also fired when the modal is dismissed either by using the close icon, by clicking an abort button which has this markup <button type="button" class="btn btn-default" data-dismiss="modal">Abort</button>, by pressing the escape key or by clicking somewhere on the .modal-backdrop. How can I distinguish a successful form submission from a dismissal of the dialog?


Solution

  • I have solved this issue in a slightly hacky way: When the form is submitted, i change the value of a custom data attribute of an element that is not part of the form being submitted. When the hidden event fires, I compare the values of my custom data attribute with the current value of the input element in the form that was displayed in the modal. If the two values differ, the modal has been dismissed, otherwise it was submitted.

    $( '#modalWithForm' ).on( 'submit', 'form', function ( e ) {
        e.preventDefault();
        $.ajax( {
            url: $( this ).attr( 'action' ),
            method: 'POST',
            data: {
                param: parseInt( $( '#input' ).val(), 10),
            }
        } ).done( function ( ) {
            $( 'label[data-custom]' ).data( 'custom', $( '#input' ).val() );
            $( '#modalWithForm' ).modal( 'hide' );
        } );
    } );
    
    $( '#modalWithForm' ).on( 'hidden.bs.modal', function () {
        var modalDismissed = parseInt( $( '#input' ).val(), 10 ) !== parseInt( $( 'label[data-custom]' ).data( 'custom' ) );
        $.ajax( {
            url: '/Update',
            method: 'POST',
            dataType: "text",
            data: {
                param: parseInt( modalDismissed ? $( 'label[data-custom]' ).data( 'custom' ) : $( '#input' ).val(), 10 )
            }
        } ).done( function ( updatedForm ) {
            $('form').empty().html(updatedForm);
        } );
    } );