Close dynamic overlay modal when client-side validation fails during submission

When a user clicks on the "Apply" button after opening a "confirm" modal, client-side validation checks all fields. However, in case of failure, the modal does not close and I am struggling to find a solution.

I attempted to use an event handler on the submit button to call myModal.hide(), but it did not work. There might be a conflict with other Bootstrap js code, but I am unsure how to proceed.

I manually tried to revert .show() by removing classes from and modal-backdrop, which prevented the modal from loading again after fixing validation errors.

I am using Bootstrap 5 beta 3.

<form method="post">
    <div class="mb-1">
        <div class="form-floating pb-0">
            <input type="text" class="form-control" asp-for="Input.Title" placeholder="Title">
            <label asp-for="Input.Title">Event title</label>
        </div>
        <span asp-validation-for="Input.Title" class="text-danger"></span>
    </div>
    <button type="button" class="btn" data-bs-toggle="modal" data-bs-target="#confirmStaticModal">

    <div class="modal fade" id="confirmStaticModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="confirmStaticModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="confirmStaticModalLabel">Apply</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>Are you sure?</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-danger" data-bs-dismiss="modal">Cancel</button>
                    <input type="submit" class="btn btn-success" value="Apply" id="confirmApplicationButton" />
                </div>
            </div>
        </div>
    </div>
</form>

Add event handler using JavaScript:

document.getElementById("confirmApplicationButton").addEventListener("click", (event) => {
    var modal = new bootstrap.Modal(document.getElementById("confirmStaticModal"));
    modal.hide();       
});

Answer №1

When you utilize new bootstrap.Modal() in this manner, you are generating a brand new Bootstrap modal that utilizes elements from an existing Bootstrap modal. This can lead to conflicts when two separate modals are linked to the same HTML elements.

To properly reference an already created modal, you should use .getInstance() like so:

var modal = bootstrap.Modal.getInstance(document.getElementById("confirmStaticModal"));

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

Share the hyperlink to a webpage with someone else

In my SQL command, I have a unique feature that retrieves the complete URL value of the current page: [##cms.request.rawurl##]. This code returns the entire URL. I need to send this address to another page and load it into a special div called "load-fac". ...

Execute two queries using MongoDB and Node.js

I'm currently facing a minor issue that I can't seem to resolve. My challenge is to pass two queries to my add_people.ejs file. While I can successfully pass one query, I am unsure of how to pass the second one. Here is an example of what I have ...

Is there a way to extract just the first line or n characters from a JSON file without having to download the entire dataset?

I am looking to extract specific information from a large JSON file that is 450 KB in size. However, I do not need to download the entire JSON file as I only require certain characters or lines from it. Is there a way to read n characters or line by line ...

Guide on setting a v-model within a v-for loop (using an example from Bootstrap Vue)

Currently, I am utilizing vue-bootstrap for creating input fields using a v-for directive. The objective is quite similar to the example provided in this link. However, I am encountering some difficulties in obtaining the data collected from these inputs i ...

Unable to successfully update DIV content in JavaScript due to incorrect file path specified

I came across this code online and it seems to be functioning properly. However, no matter what name I give the file that is supposed to load into the DIV, I consistently receive an error message stating "Object was not found." What specific steps do I nee ...

What could be the reason behind the successful execution of the Node fs.writeFile() method, yet leading to the browser receiving an empty file?

Here is an example of a callback function that appears to be sending an empty file to the browser, despite the fact that the server actually contains the word 'helloworld': router.get('/Download', function(req, res) { var fs = requ ...

Cypress - simulate multiple responses for watchPosition stub

I have a small VueJs app where clicking on a button triggers the watchPosition function from the Geolocation API to retrieve the user's position and perform some calculations with it. Now, I want to test this functionality using Cypress testing. To ...

Tips for extracting Stripe response post payment using a client-side-only integration

My current component handles sending a payment order to my stripe account on the client-side. Everything seems to be working fine, but I'm struggling to find a way to retrieve the response or token from stripe containing the order details, which I nee ...

Attempting to use jQuery on click to set the background image of a div to a base64 encoded data image

Check out what I'm working on here The first div contains html with data:image;base64 <div id="large_photo_null" style="width:50px; height:50px; background-image: url( data:image;base64,R0lGODlhR.. );" > </div> When using html, the ba ...

Show the value in the input text field if the variable is present, or else show the placeholder text

Is there a ternary operator in Angular 1.2.19 for templates that allows displaying a variable as an input value if it exists, otherwise display the placeholder? Something like this: <input type="text "{{ if phoneNumber ? "value='{{phoneNumber}}&a ...

The URL for the dynamic import in Workbox is loading incorrectly

For my laravel/vuejs application, I am utilizing workbox and babel dynamic imports. Additionally, I am making use of the laravel-mix and laravel-mix-workbox plugin to compile and generate service worker via generateSW(). The assets load correctly on the r ...

If the cursor hovers over an image, the onmouseover function does not work properly

Currently, I am developing a PHP page to display data from a database in a tabular format. Each column in the table represents an 'ATC Station'. When active, additional data is displayed upon hovering over the cell. Everything was running smooth ...

Tips for emphasizing specific text within HTML tags without highlighting the tags in Vue

I am using a tag with v-html to render HTML text and display it, like so: <div v-html="htmlText"></div> I have written code to highlight text and it works on regular text: Vue.filter('highlight', function (word, query) { ...

When multiple checkboxes are selected, the corresponding form fields will be automatically filled with shared information

When the user checks multiple checkboxes, corresponding form fields should appear based on the checkboxes selected. For example, if the user checks both the flight and hotel checkboxes, the fields for full name and last name should be displayed, while othe ...

Changing an array in PHP to a variable in JavaScript

I am struggling with converting a PHP array into a JavaScript variable using json_encode. When I print out my PHP variable: <?php $damage_array = $listing->tire_detail->damage_details; ?> It displays as: Array ( [lf] => 4 [rf] => 9 [lr ...

The code for the Express app.get() method on the server is not being updated, although other parts of the

Recently, I encountered an issue with my node js and express server that is running on localhost. I made a change in the server code from: app.get('/', (req, res) => { res.sendFile(__dirname + '/public/index.html'); }); To: app. ...

Can a reducer be designed to accommodate varying states dynamically?

Welcome to my React Application for ages 16 and above, featuring Redux. Within my bookRoom.js file, I have a component called bookRoom which is responsible for rendering a single rectangle on the screen, symbolizing a room. You can see a sample render of ...

Exporting JSON data as an Excel file in AngularJS, including the option to customize the fonts used for the

Currently, I am working on a project where I need to convert JSON data to an Excel file using JavaScript in combination with AngularJS. So far, I have successfully converted the JSON data to CSV format. However, I faced issues with maintaining the font s ...

Utilizing JavaScript: Storing the output of functions in variables

Currently in the process of learning JavaScript and aiming to grasp this concept. Analyzed the following code snippet: function multiNum(x, y){ return x * y; } var num = multiNum(3, 4); document.write(num); Decided to try it out on my own, here's ...

What are some ways I can utilize Babel in standalone mode to convert an HTML import into a variable declaration?

I am trying to utilize the Babel plugin babel-plugin-transform-html-import-to-string to dynamically transform my code in the browser client. However, the babel-plugin-transform-html-import-to-string is designed to run on node with file libraries, which are ...