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');
});
click(function(){ alert("I want this to appear after the modal has opened!"); });
To trigger the modal window, you need to use a button or a link. Then include the two data-* attributes: data-toggle="modal" opens the modal window. data-target="#myModal" points to the id of the modal.
Trigger the Modal Via data-* AttributesAdd data-toggle="modal" and data-target="#modalID" to any element.
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"));
});
As pointed out by @Rory McCrossan in a comment, the duplication of the id is the key problem of your code. To fix this, you may use index:
id="reservationModal-{{$loop->index}}"
And use start with selector like this if you want to call on each modal:
$('[id^="reservationModal-"]').on('shown.bs.modal', function (e) {
console.log('works');
});
Or, just use indexed selector to use on particular modal:
$('#reservationModal-3').on('shown.bs.modal', function (e) {
console.log('works');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With