Changing Modal Content with forEach in Node.js and EJS

Situation: Passing an array of objects (days) into an EJS template and using a forEach loop to create cards, modal trigger buttons, and modals for each iteration.

The Issue: While the cards and trigger modal buttons are generated correctly, the modal window only displays data from the first loop iteration (day[0]).

My Code:

Head Partial:

<!DOCTYPE html>
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta charset="UTF-8" />
<title>Slope Notes</title>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" integrity="sha384 H4X+4tKc7b8s4GoMrylmy2ssQYpDHoqzPa9aKXbDwPoPUA3Ra8PA5dGzijN+ePnH" crossorigin="anonymous"/>

<link rel="stylesheet" type="text/css" href="/styles.css" />

<script src="https://kit.fontawesome.com/46ee1546cc.js" crossorigin="anonymous"></script>
<head>
    <%- include('../partials/head'); %>
</head>

<body class="container">
  <header><%- include('../partials/header'); %></header>

  <% let formattedDate = ('0' + (days[0].date.getMonth()+1)).slice(-2) + '-' +
  ('0' + days[0].date.getDate()).slice(-2) + '-' + days[0].date.getFullYear() %>

  <div class="list-group page-title-container list-group-item active">
    <h2 class="page-title"><%= days[0].resortName %></h2>
    <h2 class="page-title"><%= formattedDate %></h2>
    <a class="btn-anchor btn-secondary" href="/date/new">
      <i class="fa-solid fa-plus"></i>
      Add Run
    </a>
  </div>

  <div class="card-columns">
    <% days.forEach((day, i) => { %>

    <div class="card bg-secondary container">
      <div class="row ard-header day-card-header-container">
        <div class="col"><%= day.runName %></div>
        <div class="col"><%= day.runDifficulty %></div>
        <div class="col">

<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#runModal<%= i %>" data-whatever="<%= day.id%>">
  View
</button>

<!-- Modal -->
<div class="modal fade" id="runModal<%= i %>" tabindex="-1" role="dialog" aria-labelledby="runModalLabel<%= i %>" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">

      <div class="modal-header">
        <h5 class="modal-title" id="runModalLabel<%= i %>"><%= day.runName %></h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>

      <div class="modal-body container">
        <div class="row">
          <div class="col">Rating: <%= day.runDifficulty %></div>
          <div class="col">Time (in min): <%= day.runTime %></div>
        </div>
        <div class="row">
          <div class="col">Weather: <%= day.weatherConditions %></div>
          <div class="col">Wind: <%= day.windConditions %></div>
        </div>
        <div class="row">
          <div class="col">Snow: <%= day.snowConditions %></div>
        </div>
        <div class="row">
          <div class="form-group">
            <label for="runNotes" class="form-label mt-4">Extra Notes:</label>
            <textarea class="form-control"  id="runNotes" rows="5" cols="55"><%= day.runNotes %></textarea>
          </div>
        </div>
      </div>

      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>
        </div>
      </div>
    </div>
    <% }) %>
  </div>

  <footer><%- include('../partials/footer'); %></footer>


  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>

Answer №1

Identified the solution for anyone who may come across this issue -

The problem arose from not including a unique document identifier. The modifications in the code can be seen in the modal button's data-target and the modal's id:

<!-- Button to trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#runModal<%= _day.id %>"
  View
</button>

<!-- Modal -->
<div class="modal fade" id="runModal<%= day._id %>" tabindex="-1" role="dialog" aria-labelledby="runModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">

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

Guide on sharing a Vue project with other devices within a network

I'm a complete beginner when it comes to vue.js. After working on a few small projects, I want to make sure I understand how to share a vue project with others at this stage. Typically, I know that running 'npm run serve' in my project dir ...

Struggling to create a unique grid layout with bootstrap framework

After working with Bootstrap for about a month, my HTML code may be a bit messy. The current task requires me to create a custom slick carousel in order to achieve a user interface similar to the image linked below: https://i.sstatic.net/vBIFP.png With my ...

The height of the div is set to zero within the $(document).ready() function

From what I understand, when we write JQuery code inside $(document).ready(), the code will only be executed after the DOM has finished rendering. I encountered an issue where I was trying to calculate the height of a div inside $(document).ready() but it ...

Prevent the use of exponential notation with double numbers in GWT

Is there a way to remove the exponent from a double on the client side in GWT? public double evaluate(final double leftOperand, final double rightOperand) { Double rtnValue = new Double(leftOperand * rightOperand); //Need code to remove expone ...

Dynamic element validation in JavaScript

Is there a way to validate text inputs that are generated dynamically? I currently have a "add more" link that adds new text inputs, and a link to remove them. Each input has its own unique ID. In addition, validation should require at least two text box ...

Retrieve the information from all promises

Hey there, I hope you're having a great day! So, after successfully returning multiple images using multer and testing it out, I now want to access the result variable. Take a look at how I achieved this below: req.body.images = []; const images = ...

Is there a method in React Native to include the "share" icon in my drawer instead of a button?

How can I add a "share" icon to my drawer? I attempted to insert an icon using <Ionicons name="md-share" size={24} color="black" /> instead of a Button. However, when I do this, the icon is displayed without any title, unlike what I see in the sett ...

Utilize [markdown links](https://www.markdownguide.org/basic-syntax/#

I have a lengthy text saved in a string and I am looking to swap out certain words in the text with a highlighted version or a markdown link that directs to a glossary page explaining those specific words. The words needing replacement are contained within ...

Beginner Attempting to Create a JavaScript Age Calculator

As a beginner in self-learning, I've recently started diving into the world of JavaScript. Currently, I am facing a challenge with an assignment from an online code camp that I just can't seem to figure out. Despite grasping the basics, I struggl ...

A frigid commitment sealed within a software test

I've encountered an unexpected issue while testing a service that returns a standard $q promise. Strangely, none of the promises I test seem to be resolved or rejected (specifically, the handlers from then are not being called even though the code ins ...

Steps for displaying innerHTML values conditionally with a pipe

Currently working with Angular 8 and looking to conditionally implement the innerHTML feature using a translation pipe. .html <button type="button" mat-flat-button // utilizing translate module internally [innerHTML] = "display ? (HIDE ...

Properly maintaining child processes created with child_process.spawn() in node.js

Check out this example code: #!/usr/bin/env node "use strict"; var child_process = require('child_process'); var x = child_process.spawn('sleep', [100],); throw new Error("failure"); This code spawns a child process and immediately ...

Exploring touch events and input focusing on mobile devices using JavaScript

Recently, I integrated a JS touch mapping function into one of my pages sourced from Stack Overflow. This was necessary to enable my jQuery draggables to work on iOS Safari, as drag and drop functionality was not functioning without this mapping. Here is ...

Is the alert failing to appear during the onbeforeunload event across all web browsers?

Check out the following code snippet that is functional. window.onbeforeunload = function() { someAjaxCall(); } This code block, however, does not perform as expected: window.onbeforeunload = function() { someAjaxCall(); alert("Success !!"); ...

Ensure that the authorization header is properly set for all future client requests

I need help figuring out how to automatically set the "Authorization: Bearer ..." header for user requests. For example, I save the user to the database, generate a token, and send a welcome email with the token : await user.save() const token = await use ...

Implementing a functionality in Angular.js to automatically populate an input field when a checkbox is checked

My goal is to set the respective input field to a specific value when a checkbox is checked. Below is an example of what I am trying to achieve. <label class="checkbox-inline"> <input type="checkbox" name="favoriteColors"> Five </label& ...

What is causing the issue of the page overflowing in both the x and y axis while also failing to center vertically?

I've been trying to align the <H4> styled component to the center of the page using flex-box, but it's not working as expected. I also attempted using margin:0 auto, but that only aligned the H4 horizontally. Additionally, I'm investi ...

AngularJS Accordion Component: A Handy Tool for Organ

I have been trying to implement an Accordion in my angular project by sending HTML structure from a controller. However, despite following the documentation closely, the Accordion is not displaying as expected. Here is a snippet of the code I am using: v ...

Printing the object name in CreateJS can be achieved by accessing the name property

var stage = new createjs.Stage("demoCanvas"); console.log(stage.constructor.name);//prints a <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js></script> <script src="https://code.createjs.com/createjs-2015.11.26.mi ...

Audio suddenly no longer working after transferring project to React

View my reproducible example here. This is a demonstration of the issue I am facing. Previously, when the page consisted only of static html with javascript, the sounds were functioning correctly. However, after refactoring into a React app, the sounds ha ...