Tips for indicating which content to display on template literals

Utilizing template literals to showcase some fetched data, I've successfully displayed all the necessary information on the frontend. However, certain content is hidden and meant to be toggleable. Yet, I'm struggling to figure out how to link each button specifically to the corresponding section of the HTML template that should be visible.

What would be the most effective approach to achieve this?

How can I specify which div to display upon clicking a particular button?

I've managed to capture the value of the clicked button, with the concept of linking it to the unique id of the div I intend to show. However, I am at a loss. Any guidance on how to tackle this issue would be greatly appreciated.

All I aim to do is switch the display from none to block.

const link = './data copy.json';

// const container = document.getElementById('.item-container');
fetch(link)
  .then(res => {
    return res.json();
  })
  .then(data => {
    console.log(data);

    data.forEach(gun => {
      const template = `
    <div class="ticket ticket-${gun.ticket}">
    <div class="id card"><p>${gun.gunId}</p>
  </div>
    <div class="location card">
      <p class="gun-id">${gun.location}</p> 
    </div>
    <div class="description card">
      <button class="view" value="${gun.gunId}"onclick="modalForm()">Details</button>
      <div  class="modal" id="modal-${gun.ticket}">
      <form class="modal-content" id="" data-value="${gun.gunId}"onsubmit="event.preventDefault(); validateForm();">
        <div class="form-header">
          <h1 id="" class="gun-form-name">${gun.gunId}</h1>
          <span id="" class="close" onclick="closeModal()">×</span>
          <span id="" class="back-arrow fa-lg" type="button" onclick="goBack()" role="button" aria-label="Go Back Button"><i class="fa-solid fa-arrow-left"></i>
           </span></div>
        <section class="main-content">
          <div class="container">
            <div class="card">
                <div class="wrapper">
                  <h3>${gun.gunId}</h3>
                    <div class="img">

                        <img class="gun-image"src="gun image.PNG" alt="test">
                        <div class="btn-overlay">

                        <button class="overlay-btn btn-1" value="${gun.partId.lightPipeId}"type="button">${gun.partId.lightPipeId}</button>
                        <button class="overlay-btn btn-2" value="${gun.partId.lightbugId}"type="button">${gun.partId.lightbugId}</button>
                        <button class="overlay-btn btn-3" value="${gun.partId.batteryId}"type="button">${gun.partId.batteryId}</button>
                        <button class="overlay-btn btn-4" value="${gun.partId.triggerId}"type="button">${gun.partId.triggerId}</button>
                        <button class="overlay-btn btn-5" value="${gun.partId.triggerPcb}"type="button">${gun.partId.triggerPcb}</button>
                        <button class="overlay-btn btn-6" value="${gun.partId.triggerSpring}"type="button">${gun.partId.triggerSpring}</button>
                        <button class="overlay-btn btn-7" value="${gun.partId.grayCable}"type="button">${gun.partId.grayCable}</button>
                        <button class="overlay-btn btn-8" value="${gun.partId.powerCableid}"type="button">${gun.partId.powerCableid}</button>
                        <button class="overlay-btn btn-9" value="${gun.partId.stockPcb}"type="button">${gun.partId.stockPcb}</button>
        
                    </div>
                    </div>
                    <div class="details">
                           <p class="info">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi ut iure molestiae dolores commodi amet reiciendis recusandae voluptatem porro cumque fuga excepturi eum necessitatibus, vel, assumenda alias voluptas debitis veniam.</p>
                           <p class="info">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi ut iure molestiae dolores commodi amet reiciendis recusandae voluptatem porro cumque fuga excepturi eum necessitatibus, vel, assumenda alias voluptas debitis veniam.</p> 
                           <p class="info">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi ut iure molestiae dolores commodi amet reiciendis recusandae voluptatem porro cumque fuga excepturi eum necessitatibus, vel, assumenda alias voluptas debitis veniam.</p> 
                           <p class="info">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi ut iure molestiae dolores commodi amet reiciendis recusandae voluptatem porro cumque fuga excepturi eum necessitatibus, vel, assumenda alias voluptas debitis veniam.</p> 
                           <p class="info">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi ut iure molestiae dolores commodi amet reiciendis recusandae voluptatem porro cumque fuga excepturi eum necessitatibus, vel, assumenda alias voluptas debitis veniam.</p>  
                    </div>
                    <div class="btn">
                        <button class="close-ticket"type="button">Close Ticket</button>
                    </div>
                </div>
            </div>
        </div>
        </section>
        
      </form>
    </div>
  
    </div>
  <div class="close-bt card">
    <button class="delete-button"id="${gun.gunId}">Close</button>
    </div>
    </div>
  </div>`
      document.getElementById('item-container').insertAdjacentHTML('beforeend', template);

      const modal = document.querySelectorAll(`#modal-${gun.ticket}`);
      const btns = document.querySelectorAll('.view').value;
      console.log(btns);
      for (let i = 0; i < modal.length; i++) {
        let child = modal[i];
        console.log(child);
      // switch()
    };
  });
    document.getElementById('open-tickets').innerHTML = data.length;
    document.querySelectorAll('button').forEach(button => {
      const modal = document.querySelectorAll(`#modal-${gun.ticket}`);
console.log(modal);
      button.addEventListener('click', () => {
          const fired_button = button.value;
          alert(fired_button);
          modal.style.display = "block";
          // modal2.style.display = "none";
      });

  });
})
  .catch(error => console.log(error));

this is the output: https://i.sstatic.net/CK7ez.png

Answer №1

const modalElement = document.querySelectorAll(`#modal-${gun.ticket}`);

modalElement is a NodeList[], it's better to use querySelector to get the element.

I have a feeling that gun.ticket might be undefined because you're outside of your data.forEach loop.

You can try something along these lines (not tested):

document.querySelectorAll('button.view').forEach(button => {
  button.addEventListener('click', () => {
    const modal = document.querySelector(`#modal-${button.getAttribute('value')}`);
    modal.style.display = 'block';
  });
});

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

Why are my Chrome Div regions failing to expand to their full width?

I have been searching but couldn't find an answer to my issue, so I apologize if this question has been asked before. I am working on a simple site layout and noticed that two of the div regions do not expand fully in Chrome, however, they do in Firef ...

Error message: Suitescript encountered an unexpected issue - TypeError: The function this.handleChange is not defined

For the past year, I have been immersed in Suitescript development. In my current project, I have a client script that triggers on Save for a Journal Entry. However, upon trying to save, I encounter an error message that reads "TypeError this.handleChang ...

Using HTML5 Canvas to draw intersecting polygons

Recently, I came across a polygon drawing function that caught my attention: Polygon.prototype.draw = function(ctx) { ctx.save(); ctx.beginPath(); var v = this.vertices[0] ctx.moveTo(this.position.x + v.x, this.position.y + v.y); var i ...

Impossible to create margins on both the left and right side

Check out this cool pen: http://codepen.io/helloworld/pen/BcjCJ?editors=110 I'm facing an issue where I'm unable to create both left and right margins around my datagrid. Only the left margin seems to be possible. Any suggestions on how I can f ...

Delving into the concept of the last-child element

Looking for assistance with selecting the final EC_MyICHP_Item from an HTML structure: <div class="decorator"> <div class="EC_MyICHP_Item"> <div class="text"> <h3><a target="_blank" title="" href="#">& ...

Ways to efficiently convert HTML form data into JSON format

Currently, I am in the process of developing an ecommerce platform. As part of this project, I have created a billing form to gather essential information such as email addresses and physical addresses from users. The intention behind collecting this data ...

Error message: "Named export cannot be identified"

My file structure looks like this: routes auth login index.js Login.jsx routes.js Within the routes.js file, I have the following code snippet: import { Route } from 'react-router-dom'; import { Login } from './login ...

Designing a fixed bottom footer enclosed within a wrapper that expands from the top header to the bottom footer

I have created the basic structure of my webpage using HTML / CSS. However, I now realize that I need a sticky footer that remains at the bottom of the screen with a fixed position. Additionally, I want the main content area, known as the "wrapper," to str ...

Typescript fails to recognize the imported variable within a generic type declaration

I am in the process of developing a versatile repository that can be used for every entity within the application. mongo-repository.ts import { Document, Model, Types } from 'mongoose'; type MongooseModel<T> = Model<T & Document&g ...

Is it possible to turn off GPU rasterization for a particular SVG element in Google Chrome?

There is a peculiar issue with the SVG graphic displayed on my webpage. On some computers, the complex linearGradient filling a Rect does not display all the Stops correctly, while on other computers it appears fine. I discovered that if I disable "GPU ra ...

Should I reload the entire table or insert a row manually?

This unique ajax question arises: within a table lies the users' information, displayed based on individual settings and timing. Sometimes, users instantly see the data, other times they must wait for it - their choice determines when it appears. Wha ...

Can columns in Bootstrap be used within a row without a container?

I am currently using bootstrap 4.6.0 and I have a question about the following code structure. While everything seems to be functioning correctly, I am uncertain if I should be utilizing a different container: <div class="container-fluid"> ...

"Retrieve a list of all routes that have been registered in Node.js

I am trying to retrieve a list of all registered routes in my project. Here is the code I have used for this purpose: const app = require("express"); let routers = app._router.stack .filter((r) => r.route) .map((r) => { return { ...

MUI: Issue with pseudo element appearing cropped outside of Paper container

I am facing an issue where a red arrow pseudo element '::before' is partially cut off outside its container '.MuiPaper-root'. I need the arrow to remain visible, any suggestions on how to fix this? Here is the relevant code snippet and ...

You need to click the form submit image twice in order to make it work

Struggling to get a standard opt-in form to work with an image submit button. The script works fine with a regular submit button, but the image button requires two clicks initially and then one click after unless the page is refreshed. I believe there mig ...

perform validation middleware following completion of validation checks

Looking to establish an Express REST API, I aim to validate both the request parameters and body before invoking the controller logic. The validation middleware that I have put together is as follows: const { validationResult } = require('express-va ...

Retrieve the content from paginated pages using ajax, apply a filter to it, and then add it to the existing page

My blog needs more functionality and I want to avoid using paginated pages. My idea was to extract content from these paginated pages through ajax, filter it, and add it to a specific div element. I'm not completely confident if I am on the right tra ...

Eliminate a descendant of a juvenile by using the identification of that specific juvenile

Here is the current structure I'm working with: https://i.sstatic.net/TejbU.png I want to figure out how to eliminate any field that has the id 3Q41X2tKUMUmiDjXL1BJon70l8n2 from all subjects. Is there a way to achieve this efficiently? admin.databa ...

How can you make the coordinates of the cursor track the cursor when it hovers over a rectangle?

The code provided below will constantly display the cursor's coordinates right below the cursor: function displayCursorCoordinates(e) { var x = event.clientX; var y = event.clientY; var coordinates = "(" + x + ", " + y + ")"; document.getEl ...

Enhance the Bootstrap parallelogram navbar menu by ensuring the menu items are perfectly aligned

I am working on customizing Bootstrap 5's navbar menu to create a rollover menu with parallelogram-shaped active menu items. I followed the approach recommended here, and while it works, the output is not as polished as I would like because the parall ...