How to display a Bootstrap modal when clicking on buttons within a dynamic loop of <li> tags?

I would like to share a problem I am facing with buttons in 'li' tag loop. When the info button is clicked, a particular modal should open. However, after clicking the button, the modal does not pop up on screen even though the EJS loop is functioning properly. I have inspected the generated modal code in the inspect element but it is not displaying on the screen.

<ul class="dropdown-menu" aria-labelledby="dropdownMenuButton1">
  <% item.jobApplications.forEach((applicant)=>{ %>

    <li class="border border-dark">
      <button class="infobtn badge rounded-pill bg-info text-dark" data-bs-toggle="modal" data-bs-target="#infoModal<%= applicant._id %>">info</button>
      <span class="small-bold">Name:</span>
      <span class="small"><%=applicant.candidateName %></span>

      <span class="small-bold">Percentage:</span></td>
      <span class="small"><%=applicant.candidateDegreePercent %> %</span>

    </li>
    <div class="modal fade" role="dialog" id="infoModal<%= applicant._id%>" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
      <div class="modal-dialog modal-lg">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="exampleModalLabel">Candidate Info</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            [...]
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
          </div>
        </div>
      </div>
    </div>
    <% }) %>
</ul>

Here is an image showcasing the li tag loop with an info button that should trigger the modal upon click:

Your assistance is greatly appreciated

Answer №1

Make sure to place the MODAL element outside of the UL element. This is important because when you click on the Info button, the UL element will hide. Therefore, if the Modal element is inside the UL element, it will also be hidden alongside. In simple terms, when the parent element hides, the child element will automatically hide as well.

<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5a3835352e292e283b2a1a6f746b746a">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="690b06061d1a1d1b0819295c47584759">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-U1DAWAznBHeqEIlVSCgzq+c9gqGAJn5c/t99JyeKa9xxaYpSvHU5awsuZVVFIhvj" crossorigin="anonymous"></script>

<div class="dropdown">
    <a href="#" class="btn btn-primary dropdown-toggle" data-bs-toggle="dropdown">
        User Listing
    </a>
    <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton1">
        <% item.jobApplications.forEach((applicant)=>{ %>
            <li class="border border-dark">
                <button class="infobtn badge rounded-pill bg-info text-dark" data-bs-toggle="modal"
                    data-bs-target="#infoModal_1">info</button>
                <span class="small-bold">Name:</span>
                <span class="small">
                    <%=applicant.candidateName %>
                </span>
    
                <span class="small-bold">Percentage:</span></td>
                <span class="small">
                    <%=applicant.candidateDegreePercent %> %
                </span>
            </li>
        <% }) %>
    </ul>
    <!-- Candidate info Modal -->
    <div class="modal fade" role="dialog" id="infoModal_1" tabindex="-1"
        aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">Candidate Info</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                  ...
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>
    <!-- Candidate info close -->
</div>

Answer №2

The most effective solution is to incorporate some JavaScript in this scenario. Placing the modal within a ul element poses a problem (as you are currently experiencing), and creating a separate loop for modals (as suggested in another response) will clutter the DOM with excessive elements, ultimately slowing down the page load.

My recommendation is to store the necessary details for the modal in data attributes of the button that triggers its opening. Instead of automatically opening the modal on click, trigger it manually.

  1. Assign appropriate ids to each section of the modal that needs to be populated.
  2. Click the button.
  3. Within the button's event listener, retrieve the data from its data attributes and transfer it to the modal elements (from step 1).
  4. Open the modal.

This approach ensures that your modal is dynamically filled with data without the need for multiple instances on the page.

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

"Remaining Elements" within a CSS Design

I am faced with a challenge where I have 4 elements nested inside a container element. The height of the container should be set to 100% of the browser window. The inner elements need to stack vertically, with the first two and last elements having a natur ...

Arranging HTML components in Vue.js using v-for loop

Recently, I started using vue.js and I have a requirement where I need to display an HTML structure based on API data. The structure should look like this: <div class="row"> <div><p>text1</p><img src="{{imgurl1}}" /></di ...

Tips for concealing the ID value within a URL or parameter

I just started learning Angular JS and I have a question about hiding parameters in the URL when clicking on anchor tags to send data to another controller. I don't want any ID or its value to be visible in the URL. Is it possible to hide parameters i ...

Arranging an ng-repeat list in a dynamic order

I am currently working with AngularJS and focusing on reordering the ng-repeat list. The list represents online users who can receive messages at any time. When a user receives a message, I update the UI to display the most recent message beneath their nam ...

I am currently familiarizing myself with backend routes and everything seems to be going smoothly for the first time around. However, upon attempting to revisit the site for

https://i.sstatic.net/ZOBl6.png https://i.sstatic.net/Xzhej.png Whenever I navigate from the home page to the contact page and then back to the home page, it displays an error message saying the site can't be reached. var http = require("http&q ...

Firebase and Angular 7 encountered a CORS policy block while trying to access an image from the origin

I am attempting to convert images that are stored in Firebase storage into base64 strings in order to use them in offline mode with my Angular 7/Ionic 4 application! (I am using AngularFire2) However, I encountered an error message stating: Access to i ...

Using the https module in Node.js to transfer a file to a PHP server

What is the best method to send an HTTP post request that includes a jpg file to a php server using the node https module? I attempted to use the request module, but it is unreliable (timing out most of the time) and already deprecated. Here is the functi ...

Converting a class into a cohesive JSON string within ASP.NET MVC

I have the following class: [Serializable] public class ApiRequestStatus :IEquatable<ApiRequestStatus> { public static readonly ApiRequestStatus Failure = new ApiRequestStatus("Failure"); public st ...

Surprising CSS overflow error

Recently, I've encountered a CSS overflow issue while working on a responsive webpage. The problem seems to be stemming from the navigation menu. The declaration of "overflow-x: hidden" is specifically causing the trouble... Initially, I suspected i ...

Enable a VueJS directive on-the-fly from a separate directive

My goal is to simplify the process of binding a form control to vuejs by creating a directive that handles all necessary events for tracking changes in a form field. Rather than manually adding multiple event listeners like this: <input type="text" na ...

What is the best way to trigger a function in the parent component using an event from the child component?

I'm currently immersed in learning React and am tackling the challenge of creating a game where the cards shuffle with each attempt. The card array and shuffle function are located in a parent component (using map to display the cards), while the retr ...

Unable to display canvas background image upon webpage loading

Currently working on a JavaScript project to create a captcha display on a canvas. The issue I'm facing is that the background image does not load when the page initially opens. However, upon hitting the refresh button, it functions as intended. Here& ...

What is the best way to access the tooltip text in Reddit?

Currently, I am in the process of developing a Selenium web scraping tool specifically for Reddit. However, I am encountering some challenges in extracting the timestamp displayed in the image. from selenium import webdriver from webdriver_manager.chrome i ...

Using values from a preexisting array to generate new arrays in JavaScript

I'm currently facing a challenge in JavaScript where I need to generate arrays based on the values of another array. For instance, I have an array of dates in string format (dates) listed below: ["30/09/2015", "31/10/2015", "30/11/2015", "31/12/2015 ...

Troubleshooting Issue: Google Map not resizing correctly when window size changes

Utilizing media queries, I have implemented an adaptive layout on my website. However, when I adjust the size of the browser window beyond a specific media query, the google map begins to malfunction (refer to the image) My Solution: CSS: #googleMap2{d ...

Binding data conditionally based on a property in Vuejs

My situation involves a component that includes a child component with bindable properties. Here is an example: <template> <div> <Child :bar="foo"></Child> </div> </template> <script> export default { na ...

Different Ways to Make Custom Checkboxes Overlap with Labels in CSS

Hello everyone, I am currently diving into the world of CSS and HTML. My goal right now is to create a custom checkbox with a list of options. During my research, I stumbled upon an example on how to create custom checkboxes at this link. However, when imp ...

Instructions for outputting a string to the console in Javascript

I am looking for a versatile method to write a string to standard output in a portable manner, without automatically adding newlines at the end. I prefer it to utilize UTF-8 encoding and be compatible with: jrunscript (from any JDK) Rhino node.js Curren ...

MongoDB's approach to denormalizing data

As I delve into the world of MongoDB, I find myself pondering over data duplication. In the realm of SQL, the norm is to normalize data - keeping categories and products in separate tables linked by a join. However, in MongoDB, is it true that this appro ...

What is the correct way to utilize the Vuex mutation payload object effectively?

I have two input fields where I can enter a value to search for either the name of a company or the location. The search functionality works when only one argument is provided in the foundJobs mutation and action. However, when the payload contains an obje ...