Reputation: 25
I would like to close all modals with a line of code, I have a code is like this:
closeModals() {
$('#new-user').modal('hide');
$('#new-project').modal('hide');
$('#new-task').modal('hide');
}
But the problem is that I have more than 20 modals in my project, is there a way of closing all modals without repeating the id of each modal ? Thank you !
Upvotes: 0
Views: 1840
Reputation: 2146
What worked for me in Bootstrap 5 is a bit different:
function close_modals(){
document.querySelectorAll('.modal').forEach(function(modalElem) {
const myModal = bootstrap.Modal.getOrCreateInstance(modalElem);
myModal.hide();
});
}
The difference is in the getOrCreateInstance, which will either create a new instance (if there wasn't one) or get the active one (which is likely the one you really wanted to close anyway)
Upvotes: 3
Reputation: 11
You can select via javascript the class of all your modals and close them.
Bootstrap < 5
$('.modal').modal('hide');
Bootstrap >= 5
document.querySelectorAll('.modal').forEach(function(modalElem) {
const myModal = new bootstrap.Modal(modalElem);
myModal.hide();
});
Upvotes: 1
Reputation: 160
If you can add class to the element you can call just this.
$('.my-modals').modal('hide');
Upvotes: 1