Tips for concealing Bootstrap 5 modal exclusively after successful completion

Utilizing the power of Bootstrap 5

I have successfully implemented a modal that shows up when #truck_modal is clicked, thanks to the following JavaScript code:

(this snippet is located at the beginning 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();
    });
})

However, I encountered a challenge when trying to make the modal hide only if the AddTruck function is successful. Here's my attempt:

function AddTruck() {

    ... performing some validations ...

    fetch('/inbound/add_truck', {
        
        ... fetching data ...

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

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

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

            modal.hide();
            alert('Success!!!')
        }

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

}

Despite several attempts, including creating a separate function to hide the modal, I still face issues. Any suggestions on how to solve this problem would be highly appreciated.

Could this be a built-in feature of Bootstrap or am I missing something important?

UPDATE

Below are the JS scripts, Bootstrap, and jQuery included in my project:

<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/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="096b66667d7a7d7b6879493c27392739246b6c7d683b">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-b5kHyXgcpbZJO/tY9Ul7kGkf1S0CWuKcCD38l8YkeH8z8QjE0GmW1gYU5S9FOnJ0" crossorigin="anonymous"></script>
<script src="{% static 'utils.js' %}"></script>

In an effort to hide the modal, I also added the line $('#truck_modal').modal('hide'); within the else block of my code.

Answer №1

I once faced a similar issue, and it turns out the problem was located between the chair and the keyboard. (Maybe with a slight blame on the poorly written documentation as well.)

It seems that your modal already exists. So, instead of creating a new one, you should access the existing modal like this:

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

By doing this, you can effectively handle custom Modal (Dropdown, Popover, ...) functions. This detail is often overlooked in the documentation, so it's worth highlighting.

Answer №2

If you need to conceal a Bootstrap modal, you can utilize the following code:

const modal = new bootstrap.Modal(document.getElementById('myModalId'));
modal.hide();

Answer №3

According to the response from @solilim,...

function closePopup(id) {
    const popupElement  = document.querySelector('#'+id);
    const popupInstance = bootstrap.Popup.getInstance(popupElement);

    if (popupInstance ==  null){
       return;
    }

   popupInstance.close();
}

function openPopup(id) {
    const popupElement  = document.querySelector('#'+id);
    let   popupInstance = bootstrap.Popup.getInstance(popupElement);

    if (popupInstance ==  null){
       popupInstance = new bootstrap.Popup(popupElement, {
        backdrop: 'static'
       });
   }

   popupInstance.open();
}

Answer №4

It turned out to be much simpler than I thought. It's amazing that I wasted two whole days on this... 🤦‍♂️

All I had to do was pass the modal as a parameter to the AddTruck function like this:

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

And then calling modal.hide() inside the AddTruck function worked like a charm.

Answer №5

Give this a shot, it did the trick for me. I successfully concealed my modals with the help of jQuery

$('#truck_modal').modal('hide');

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Vue components or elements within the v-html directive allows for dynamic rendering

One of the challenges I'm facing involves handling data from a blog post, specifically the user-submitted text stored in post.text. Similar to Twitter, users can mention other users using syntax like I am tagging @user1 in this post. My goal is to aut ...

Retrieve the string data from a .txt document

I am facing an issue with my script that retrieves a value from a .txt file. It works perfectly fine when the value is a number, but when trying to fetch text from another .txt file, I encounter the "NaN" error indicating it's not a number. How can I ...

Choosing Issues

My selectpicker is displaying data outside the dropdown menu before making a selection. The data appears both inside and outside of the dropdown. Can someone please help me identify the issue and guide me on how to fix it? <select class="selectpick ...

Animate the tubular geometric pathway by continuously updating its values

When creating a TubeGeometry, I supplied a SplineCurve3 / CatmullRomCurve3 path as a parameter. My goal is to update the position of each point on the path using geometry.parameters.path.points[1].y += 0.01; within the requestAnimationFrame loop. Even tho ...

The function you are trying to call is not valid... the specified type does not have any call signatures [ts 2349

Having some trouble using functions from Observable Plot example with a marimekko chart in my TypeScript project. I encountered an error on this particular line: setXz(I.map((i) => sum.get(X[i]))) The code snippet causing the issue is as follows: fu ...

Maintain dropdown menu visibility while navigating

I'm having an issue with my dropdown menu. It keeps sliding up when I try to navigate under the sub menu. I've spent all day trying to fix it, testing out various examples from the internet but so far, no luck. Any help would be greatly apprecia ...

What is the process for setting environment variables in a Svelte project?

I'm brand new to working with Svelte and I want to incorporate environment variables like base_url into different components. I've read that I can set up a store to hold these values, for example: const DataStore = writable([ { base_url: & ...

Anticipated request for spy navigation with path '/members' was expected, but unfortunately was not triggered

I am facing an issue with a service method that performs an HTTP delete operation. The expected behavior is that upon successful deletion, the page should be redirected to another location. However, during testing, I noticed that the router navigation func ...

Adjust the href attribute of a link dynamically using the value input from a text field immediately

Is there a way to dynamically change the href attribute of a link when a user types in an input field? And is it possible to detect when a user pastes content into the input field as well? Would appreciate any suggestions on how to accomplish this using j ...

I'm currently utilizing lint in my Angular 2+ project. Is there a way to arrange the constructor parameters in alphabetical order

I am struggling to organize the constructor parameters in TypeScript while using TSLINT with Angular9. I am looking for a rule similar to member-ordering that can help me sort them effectively. constructor( // Sort these private readonly router: R ...

Bootstrap 5 - Achieve automatic column width within a row

In my Bootstrap 5 setup, I have a variety of pages that have different column layouts - sometimes 2 columns, sometimes 3. The template system I'm using dynamically adjusts the layout to accommodate the need for a third column when necessary. <div ...

Sending an AJAX request when refreshing a page segment

I have recently registered, but I have been a silent reader for years. Up until now, I have managed to find the answer to all my questions by searching on Stack Overflow. However, I am faced with a new challenge... I am new to AJAX and I am in the process ...

Rendering HTML is not supported by AngularJS on Android 19 with version 4.4.4 and Safari 8.0.5

I have been working on an AngularJS app that is being displayed in a Webview on Android. Everything was functioning properly until yesterday when I started encountering issues with Angular not rendering the DOM correctly. I have tested the app on various v ...

Can you identify this numerical category?

Can you identify this number type? console.log(0100); // output 64 console.log(050); // output 40 console.log(010); // output 8 In a hexadecimal system, it would be: 0100 = 256 050 = 80 010 = 16 ...

A handy feature of HTML5 is the dataset attribute, which

Is there a way to restrict the height of the dataset dropdown list in HTML? When using <input list="datalist"> with numerous elements, some might not be visible. Is it possible to limit the size of the list and enable vertical scrolling to display al ...

In the absence of a value

In my code, I've implemented a functionality that saves the user's input into local storage and displays it in a specific ID. However, I want to make sure that if the input field is left empty, the user is prompted to enter their name. function ...

Extending a universal design concept to a new theme within the MUI (Material UI) framework

I have implemented MUI's ThemeProvider and set up a Themes.js file. Within this file, I have defined the globalTheme for managing global styles such as typography and border-radius. My intention is to extend the properties of globalTheme to both light ...

Encountering a 404 XHR Error when attempting to add a component in Angular 4.1.0 within Plunker

Having some trouble setting up Angular 4 on Plunker and adding a new component. The following URL is where I'm working: https://plnkr.co/edit/1umcXTeug2o6eiZ89rLl?p=preview I've just created a new component named mycomponent.ts with the necessar ...

The configuration error occurred for the `get` action due to an unexpected response. Instead of an object, an array was received

Despite numerous attempts, I am struggling to find a solution that works for me. In my Courses controller, I am using the Students service and Staff service to access my staff and student objects. My goal is to retrieve the staffs and students objects in o ...

The elements that meet the first condition are the only ones displayed by my filter

I'm having trouble figuring out the best way to describe this scenario: I have a list of bases, each with a list of connectors (which could be one or more). I created a filter to sort my bases by their connectors, and here's what my method looks ...