Is there a way to switch between modals with the same ID using JavaScript?

I currently have a modal window open which contains a paginated list. Within this modal, I have next/previous buttons that are supposed to display new content.

Since this functionality needs to work on multiple pages, I can't include HTML code for the modals next and prev inside the initial modal as Bootstrap recommends.

My workaround involves closing the current modal and opening a new one using JavaScript. This method works quite well except for one issue: every time I close a modal, the modal itself closes but a grey semi-transparent background remains, adding up each time a new modal is opened.

Due to the framework and template constraints, these modals share the same id. I attempted to use different modal ids for each page, but encountered similar results.

The question at hand is why does this semi-transparent div linger when the modal is closed? Is there an alternative approach to tackle this issue? (I believe embedding the html code for next/prev within the modal is not feasible).

Included below is my code snippet, along with other options I've experimented with, all yielding comparable outcomes:

openModalWindow: function(route, modalId)
{
    $.ajax({
        type: "GET",
        url: route, 
        success: function(data){
                                $('#' + modalId).remove();
                                $('body').append(data);
                                $('#' + modalId).modal('show');
                               }
      });
},
closeModalWindow: function(modalId)
{
    // $('#' + modalId).remove();
    // $('#' + modalId).on('hidden.bs.modal', function () {$('#' + modalId).modal('show')});
    
    let myModal = new bootstrap.Modal(document.getElementById(modalId),
                                      {keyboard: false});

    //myModal.dispose();
    myModal.hide();

},
openOtherModal: function(closeModalId, newRoute)
{
    closeModalWindow(closeModalId);
    openModalWindow(newRoute, closeModalId);
},

And the previous/next buttons inside the modals are:

    <a href="javascript:void(0)" onclick="AdminUI.openOtherModal('clientfile-listby'
                                                                 'list.php/page-1')">
        &lt; Prev.
    </a>
    <a href="javascript:void(0)" onclick="AdminUI.openOtherModal('clientfile-listby'
                                                                 'list.php/page+1')">
        Next. &gt;
    </a>

Answer №1

Dealing with modal windows can be a bit tricky. At my workplace, we typically use the modal hide method:

closeModalWindow: function(modalId) {
    $('#' + modalId).modal('hide');
},

If you find that your modal is not closing properly, another approach is to directly remove the backdrop class:

closeModalWindow: function(modalId) {
    $('#' + modalId).modal('hide').on('hidden.bs.modal', function () {
        $('.modal-backdrop').remove();
    });
},

I also recommend using the $('#') syntax to ensure that you are referencing the correct element.

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 jQuery to validate the existence of a link

Within my pagination div, I have links to the previous page and next page. The link to the previous page is structured as follows: <span id="previous"><a href="www.site.com/page/1" >Previous</a>. However, on the first page, there will be ...

Capturing mouse clicks in Javascript: a guide to detecting when the mouse moves between mousedown and mouseup events

I have been working on a website that features a scrolling JavaScript timeline, inspired by the code found in this tutorial. You can check out the demo for this tutorial here. One issue I've encountered is when a user attempts to drag the timeline an ...

The MDBDataTable features header sections at both the top and bottom, but the filters UI seems to be

Currently, I am working with MDBDataTable and encountering an issue with the double heading that appears both on top and bottom of the table. I am unsure how to remove it. The code snippet in question is as follows: There is a function that retrieves and ...

How can the Angular Js framework be utilized to create a pop-up feature in combination with Bootstrap?

I'm currently working on a website using AngularJS and Bootstrap. When the site is loading, I make a server call to fetch some data. This process takes some time, and during this interval, I want to display a pop-up message indicating that the user s ...

incorporate setInterval() with a dynamic variable serving as the millisecond value

During initialization of the component, a value is fetched from the ngrx store and used as a configuration. this.storeService.selectMConfig().subscribe(res => { if (!res) return; const refreshValue = Number(res.items[0].value) * ...

Click on an element that is nested within another element that can also be clicked on

I'm facing a challenge while attempting to create an accordion inside another accordion. The issue arises with the nested elements and their behavior upon clicking. Essentially, I have a parent div with the class .applicant, which expands on click by ...

Amazon S3 Landing Page Featuring Contact Form

Although S3 is not a fileserver, it serves as an excellent tool for managing static websites. The majority of my projects are 99% static, making it ideal for this particular project. As an AWS Solutions Architect, I am struggling to find the most straightf ...

Here's a way to run JavaScript code from a <script> tag included in an AJAX response

Currently, I am making a jQuery GET request in this format: $.get($(this).attr("href"), $(this).serialize(), null, "script"); I'm expecting the response to be enclosed in script tags. I know that the browser won't run the response if it contai ...

Whenever I attempt to start my ReactJS project using the command line with `npm run it`, I keep encountering an error

Encountered an issue with the webpack-dev-server script while working on my project. Ensure that your node.js and npm versions are up to date. If they are, the problem might lie within the reactjs package rather than npm itself. Kindly inform the author ab ...

Executing a PHP function every second using JS/Ajax: A step-by-step guide

Currently, I am utilizing the Highcharts API from http://www.highcharts.com/demo/dynamic-update to create a dynamic graph that reflects server load on my web panel. I have developed a PHP function called get_server_cpu_usage() which retrieves the current ...

tips for adding text to an input field after it has been submitted

Is there a way to automatically add text to an input field after the user has entered their information? For example, if a user types "youtube.com" into a search bar, could the input then apply ""? ...

Converting string patterns to regular expressions

I am utilizing mongodb to store data. My requirement is to save complete regular expressions as strings: { permissions: [{ resName: '/user[1-5]/ig', isRegex: true }] } Although I am aware of the existence of the module mongoose-rege ...

Angular does not assign the ng-invalid-class to the input

In order to register custom validation methods for custom form elements, we use extra directives as shown below: <ng-form name="validatorTestForm"> <our-input-directive name="validatorTest" ng-model="ourModel"/> ...

Causes of the error message 'TypeError: res.render is not a function'

I have set up an express application with the following code: var express = require('express'); var router = express.Router(); var passport = require('passport'); var User = require('../models/user'); var request = require(&a ...

Organizing data with JavaScript: Transforming a flat array into nested JSON structures

In my front-end TypeScript file, there is a list called poMonths: 0: {id: 1, companyName: "company14", companyId: 14, flActive: true, purchaseMonth: "2019-12-15T00:00:00", purchaseMonthString: "Dec-2019" , year: 2019, month: "December"} 1: {id: 2, company ...

Steps for including a solid bottom border in a toggled navigation bar that is responsive

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document&l ...

Tips for repairing a side bar and header with CSS when using a JS & jQuery scroller

I am working on a layout design and my goal is to have the left sidebar, right sidebar, and header remain fixed in place. Here is the CSS code I am using : #container { padding-left: 200px; /* Left Sidebar fullwidth */ padding-ri ...

Uploading files with the help of Formik and the Material-UI stepper component

When attempting to upload a file, the entire component refreshes each time. The process involves 3 steps: the first step captures the user's name, the second step collects their address, and the third step allows them to upload a profile picture. Howe ...

Guide to making two text boxes with SimpleDialog in jQuery Mobile

I came across the link below, but unfortunately it's not working for me. jQuery Mobile SimpleDialog with two Inputs? Is there anyone who can assist me after reviewing the code snippet provided below? <script type="text/javascript> ...

Unable to include Electron in a React component for ipcRenderer

I've been attempting to import the ipcRenderer into a react component in order to communicate with the electron side. However, I'm facing issues trying to import electron. Here are some of the attempts I've made: import { ipcRenderer } from ...