How to hide Bootstrap 5 modal only on success?
Asked Answered
A

5

7

Using bootstrap 5

I have a modal which I show when #truck_modal is clicked which works just fine like so:

(this code is at the top of my js file)

document.addEventListener('DOMContentLoaded', function() {
    document.querySelector('#add_truck').addEventListener('click', AddTruck);

    const truck_modal = document.querySelector('#staticBackdrop');
    const modal = new bootstrap.Modal(truck_modal, {
        backdrop: 'static'
    });

    document.querySelector('#truck_modal').addEventListener('click', () => {
        modal.show();
    });
})

Now, if I add the following to the above function it works.

document.querySelector('#add_truck').addEventListener('click', () => {
     modal.hide();
});

But here it runs when #add_truck is clicked regardless if the AddTruck function was successful or not, I only want it to hide if the AddTruck function is successful, so I tried the following.

function AddTruck() {

    ... some validations ...

    fetch('/inbound/add_truck', {
        
        ... some fetch code ...

    })
    .then(response => {
        jsonResponse = response.json();
        status_code = response.status;

        // console.log(jsonResponse);
        // console.log(status_code);

        if(status_code != 200) {
            alert('There was an error!');

        } else{
            origin.value = '';
            produce.value = '';
            license_num.value = '';
            loaded_weight.value = '';

            // document.querySelector('#add_truck').addEventListener('click', () => {
            //     modal.hide();
            // });
            modal.hide();
            // hideFunc();

            alert('Success!!!')
        }

        return status_code
    })
    .catch(error => {
        console.log(error)
    })

}

Even tried this:

function hideFunc() {
    const truck_modal = document.querySelector('#staticBackdrop');
    const modal = new bootstrap.Modal(truck_modal, {
        backdrop: 'static'
    });

    modal.hide();
}

What am I doing wrong here? Please help...

Or is this a feature?

EDIT

These are my js, bootstrap and jquery scripts

<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-b5kHyXgcpbZJO/tY9Ul7kGkf1S0CWuKcCD38l8YkeH8z8QjE0GmW1gYU5S9FOnJ0" crossorigin="anonymous"></script>
<script src="{% static 'utils.js' %}"></script>

And I added $('#truck_modal').modal('hide'); to the else block where I'm trying to hide it.

Apiarist answered 9/3, 2021 at 5:57 Comment(0)
L
42

I had this problem too and sadly it was between chair and keyboard :( (And maybe a little bit in not clearly written docs. Just to justify myself :) )

Your modal already exists. So calling:

function hideFunc() {
    const truck_modal = document.querySelector('#staticBackdrop');
    const modal = new bootstrap.Modal(truck_modal, {
        backdrop: 'static'
    });

    modal.hide();
}

Will not work, because by this you are creating new modal. So, you create a new modal, set its backdrop to static and then you hide it. Without even showing it.

Instead of creating a new one, you want to call / address the already existing one, by using bootstrap.Modal.getInstance. Like this:

function hideFunc() {
    const truck_modal = document.querySelector('#staticBackdrop');
    const modal = bootstrap.Modal.getInstance(truck_modal);    
    modal.hide();
}

This way you can make yourself custom Modal (Dropdown, Popover, ...) handlers. It is only briefly described in the documentation, so it is easy to overlook it.

Lavish answered 9/3, 2021 at 11:8 Comment(8)
const modal = bootstrap.Modal.getInstance(truck_modal); modal.hide(); is absolutely what you are looking for if you've searched for this question online.Pejoration
You can also use the function Modal.getOrCreateInstance(truck_modal) to get or get and create the modal instance.Amain
saved my life. Thank you!Singh
This answer should be the accepted answer.Kinross
I'm trying to do this on Vue. It says bootstrap is not defined. Any other way to do this?Zymogenesis
@BalasubramanianS I have no experience with Vue js, but similar question was answered here: https://mcmap.net/q/321621/-bootstrap-5-referenceerror-bootstrap-is-not-definedLavish
Thanks. I finally did a similar solution.Zymogenesis
it seems that there is more than one such gasket between the chair and the monitor, and that's meFaxun
T
6

To hide Bootstrap modal, use this code snippet

var myModal = bootstrap.Modal.getOrCreateInstance(document.getElementById('myModalId'));
myModal.hide();
Trothplight answered 20/5, 2022 at 13:42 Comment(0)
C
1

Based on @solilim answer,...

function hideModal(id) {
    const modal_el  = document.querySelector('#'+id);
    const modal_obj = bootstrap.Modal.getInstance(modal_el);

    if (modal_obj ==  null){
       return;
    }

   modal_obj.hide();
}

function showModal(id) {
    const modal_el  = document.querySelector('#'+id);
    let   modal_obj = bootstrap.Modal.getInstance(modal_el);

    if (modal_obj ==  null){
       modal_obj = new bootstrap.Modal(modal_el, {
        backdrop: 'static'
       });
   }

   modal_obj.show();
}
Counterinsurgency answered 15/12, 2022 at 11:11 Comment(0)
A
0

So this was actually very easy. Can't believe I spent two days on this... 🤦‍♂️

I just sent the modal as a param to the AddTruck function like so:

document.querySelector('#add_truck').addEventListener('click', () => AddTruck(modal));

And then modal.hide() worked inside the AddTruck func.

Apiarist answered 9/3, 2021 at 7:50 Comment(0)
B
-8

try this, it worked for me. I hide my modals using jquery

$('#truck_modal').modal('hide');
Brutalize answered 9/3, 2021 at 6:16 Comment(7)
This doesn't work. And I think BS5 dropped jquery.Apiarist
did you add the jquery script? <script src="code.jquery.com/jquery-3.5.1.js"></script>Brutalize
BS5 did not drop jquery I am currently using it. If scripts are added in the incorrect order it may cause issuesBrutalize
jquery loaded correctly without any errors, but the modal is still not being hiddenApiarist
could paste the changes you made?Brutalize
I pasted the changes as edit in the questionApiarist
even if I included jquery it is not workingTransport

© 2022 - 2025 — McMap. All rights reserved.