I found this question about how to avoid the overlay of the second modal. So I have applied the @A1rPun fix:
$(document).on('show.bs.modal', '.modal', function () {
var zIndex = 1040 + (10 * $('.modal:visible').length);
$(this).css('z-index', zIndex);
setTimeout(function() {
$('.modal-backdrop').not('.modal-stack').css('z-index', zIndex - 1).addClass('modal-stack');
}, 0);
});
$(document).on('hidden.bs.modal', '.modal', function () {
$('.modal:visible').length && $(document.body).addClass('modal-open');
});
Now when I press the Esc
button the modal form in the back is closed. However, the form ahead is the one that must be closed.
I have tried to fix it by adding some listener like the below code. But if I do this, sometimes both forms are closed at the same time. Maybe because there is another listener already.
$(document).ready(function() {
$(window).keydown(function(event){
if (event.keyCode == 27) { // Esc code
if ($('.modal-form').length > 0) {
let z = 0;
let modal_to_close = null;
$('.modal-form').each(function () {
let current_z = parseInt($(this).css('z-index'), 10);
if (z < current_z) {
z = current_z;
modal_to_close = $(this);
}
})
modal_to_close.find('.close').click();
}
}
});
});
How can I make this work well? Should I override the Bootstrap keydown listeners? How to do it?
Note: I am using Bootstrap v3.3.7