jquerybootstrap-modal

Binding event before Bootstrap Modal show


I have a simple Bootstrap modal:

<div id="mymodal" class="modal fade">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h3>Modal header</h3>
    </div>
    <div class="modal-body">
    ...
    <div>
</div>

I have attached it with a button using data-toggle

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#mymodal"> Toggle</button>

Now when the button is clicked the modal will show up. The modal body contains a div which needs to be pre-populated. I used below code to do this:

$('#mymodal').on('shown.bs.modal', function(){
    generate_modal_body();    
})

But above code is not working.

Surprisingly, if I add click event on the button on modal, it can triggers the generate_modal_body(). I have checked similar questions here but could not find satisfactory answer.

Please let me know if I am missing something obvious.


Solution

  • Please attach the shown event of bootstrap modal in the document ready function.

    <script type="text/javascript">
     $(document).ready(function () {
        $('#mymodal').on('shown.bs.modal', function() { 
           generate_modal_body();
        }) ;
     });
    </script>