Skip to content

How can I call a function when a Bootstrap modal is open?

I use Boostrap 3.7 and Blade (Laravel 5.5).

I’m trying to display console.log('works') when my boostrap modal opens but it didn’t work.

HTML :

@foreach(...)

    ...

    <div class="modal fade" id="reservationModal" tabindex="-1" role="dialog" aria-labelledby="reservationModal" aria-hidden="true">
        <div class="modal-dialog">
            ...
        </div>
    </div>
@endforeach

JS :

$('#reservationModal').on('shown.bs.modal', function (e) {
    console.log('works');
});

I followed this doc : https://getbootstrap.com/docs/3.3/javascript/#modals

And I already read that : Calling a function on bootstrap modal open

Thank’s for help !

EDIT 1:

I solved the problem with this code :

$(document).on('show.bs.modal', '#reservationModal', function (e) {
    console.log('works');
});

But how to differenciate modals (because they are into foreach loop)?

Something like :

$(document).on('show.bs.modal', '#reservationModal-specificId', function (e) {
    console.log('works');
});

Answer

I think your event listeners are created before HTML printing. So try this code.

$(document).on('show.bs.modal', '#reservationModal', function (e) {
    console.log('works');
});

$(document).on(‘show.bs.modal’, ‘#reservationModal’, function (e) {});

the bold characters will help to identify your modal

ANSWER FOR YOUR UPDATED PART

run the loop and create your modal as follows

<div class="modal fade reservationModal" id="reservationModal1" tabindex="-1" role="dialog" aria-labelledby="reservationModal" aria-hidden="true">
    <div class="modal-dialog">
        ...
    </div>
</div>

<div class="modal fade reservationModal" id="reservationModal2" tabindex="-1" role="dialog" aria-labelledby="reservationModal" aria-hidden="true">
    <div class="modal-dialog">
        ...
    </div>
</div>
...... and so on

Give reservationModal as class

and id as an incremented value appended to it

$(document).on('show.bs.modal', '.reservationModal', function (e) {
    console.log($(this).attr("id"));
});