Collapse or expand nested rows within a dynamic table using Bootstrap Collapse feature

I am currently working on creating a dynamic leaderboard table for a sports league using data from a SQL database. The league consists of multiple teams, each team has different players (with some players belonging to more than one team), and players earn money by participating in various events. The goal is to display the total earnings for each team initially. When a team row is clicked, the details of that team's players should be revealed. Similarly, clicking on a player row should show the event details for that specific player on their team. Clicking again on a row should hide the displayed data. I’m facing challenges with dynamically setting the data-target and id attributes. While hard-coding these values works as expected, it reveals all data across all parents instead of just the selected parent. I have provided a simplified array example in place of querying the actual database. Thank you!

https://jsfiddle.net/gistewart/e9qyLv20/

const arr = [{
    teamName: "team1",
    teamEarnings: "$1700",
    teamPlayers: [{
        playerName: "player1",
        playerEarnings: "$1000",
        events: [{
          eventName: "event1",
          eventEarnings: "$400"
        }, {
          eventName: "event2",
          eventEarnings: "$600"
        }],
      },
      {
        playerName: "player2",
        playerEarnings: "$700",
        events: [{
          eventName: "event2",
          eventEarnings: "$500"
        }, {
          eventName: "event3",
          eventEarnings: "$200"
        }],
      }
    ],
  },
  {
    teamName: "team2",
    teamEarnings: "$2900",
    teamPlayers: [{
        playerName: "player1",
        playerEarnings: "$900",
        events: [{
          eventName: "event1",
          eventEarnings: "$800"
        }, {
          eventName: "event3",
          eventEarnings: "$100"
        }],
      },
      {
        playerName: "player3",
        playerEarnings: "$2000",
        events: [{
          eventName: "event2",
          eventEarnings: "$1250"
        }, {
          eventName: "event3",
          eventEarnings: "$750"
        }],
      }
    ],
  }
]

function displayLeaderboard(arr) {
  for (let i = 0; i < arr.length; i++) {
    $(".leaderboard-container").append(
      "<tr data-toggle='collapse' data-target='#demo1' class='clickabe'><td>" + arr[i].teamName + "</td><td>" + arr[i].teamEarnings + "</td></tr>"
    )
    for (let j = 0; j < arr[i].teamPlayers.length; j++) {
      $(".leaderboard-container").append(
        "<tr class='level2 hiddenRow collapse' id='demo1' data-toggle='collapse' data-target='#demo2' class='clickable'><td>" + arr[i].teamPlayers[j].playerName + "</td><td>" + arr[i].teamPlayers[j].playerEarnings + "</td></tr>"
      )
      for (let k = 0; k < arr[i].teamPlayers[j].events.length; k++) {
        $(".leaderboard-container").append(
          "<tr class='level3 hiddenRow collapse' id='demo2' ><td>" + arr[i].teamPlayers[j].events[k].eventName + "</td><td>" + arr[i].teamPlayers[j].events[k].eventEarnings + "</td></tr>"
        )
      }
    }
  }
}

displayLeaderboard(arr);
.level2 {
  font-size: 0.9em;
  color: blue;
}

.level3 {
  font-size: 0.8em;
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet" />


<body>
  <div class="container">
    <table class="table leaderboard-container">
      <thead>
        <tr>
          <th scope="col">Team</th>
          <th scope="col">Earnings</th>
        </tr>
      </thead>
      <tbody>
      </tbody>
    </table>

Answer №1

To ensure proper functionality, it is important to assign unique identifiers to each collapse element called from the parent container:

  function displayLeaderboard(arr) {
    for (let i = 0; i < arr.length; i++) {
      $(".leaderboard-container").append(
        "<tr data-toggle='collapse' data-target='#demo"+ i +"' class='clickabe'><td>" + arr[i].teamName + "</td><td>" + arr[i].teamEarnings + "</td></tr>"
      )
      for (let j = 0; j < arr[i].teamPlayers.length; j++) {
        $(".leaderboard-container").append(
          "<tr class='level2 hiddenRow collapse' id='demo"+ i +"' data-toggle='collapse' data-target='#demo-"+ i +"-"+ j +"' class='clickable'><td>" + arr[i].teamPlayers[j].playerName + "</td><td>" + arr[i].teamPlayers[j].playerEarnings + "</td></tr>"
        )
        for (let k = 0; k < arr[i].teamPlayers[j].events.length; k++) {
          $(".leaderboard-container").append(
            "<tr class='level3 hiddenRow collapse' id='demo-"+ i +"-"+ j +"' ><td>" + arr[i].teamPlayers[j].events[k].eventName + "</td><td>" + arr[i].teamPlayers[j].events[k].eventEarnings + "</td></tr>"
          )
        }
      }
    }
  }

  displayLeaderboard(arr);

We hope this explanation clarifies any doubts you may have.

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

Tips for creating a captivating full-screen parallax section on your website

Is there a way to make the first section of a parallax site full screen? I've been scouring the internet for a solution to this problem, but I'm not having any luck. Almost every parallax site I come across has their first section full screen, a ...

Checkbox selection causing Bootstrap accordion to collapse

Hey everyone, I'm currently working with Bootstrap 5 accordion and facing an issue where the input checkbox is triggering the "collapse" event of the accordion. I attempted to relocate the checkbox outside the scope of the accordion button but that so ...

A datatable was designed to set a background color for every row, regardless of any specified conditions for selecting which rows to apply

I have a challenge with setting background colors for rows in a datatable based on the data retrieved from the server. When fetching dynamic data through ajax, it is successfully displayed in the table. However, the color applied to all rows, regardless o ...

What steps can be taken to modify this jQuery code so that any changes made are also saved to localStorage

I have successfully used jQuery to change the background color of all my divs with the same class (userNumber1) when I check its checkbox. However, I am now looking for a way to save these changes to localStorage, so that they persist each time the page is ...

The response from the $.ajax call encounters an issue with the content-Type being set to application/json when the content is

Having a bit of trouble with the response content type. Here's the jQuery ajax request code I'm using: var settings = { dataType: 'json', url: 'services/loadTemplate.ashx', data: JSON.stringif ...

The Json request is invalid because it contains the @ symbol

After validating the Json data online, it appeared to be correct. However, when I attempted to call the json array key, the editor showed a Parsing error: Unexpected character '@' The editor in question is Visual Studio Code, and it seems as tho ...

Tips for aligning a div (or any other content) in the center of a

I recently added a small div to my webpage to display 3 options in a stylish way, but I'm encountering an issue - the box is appearing on the left side instead of the center. I have tried using various CSS properties like align-items, align-content, a ...

Ensure that Mathjax underscores are consistent with the height of other characters

Presented below is the latex code being used with Mathjax. \class{mathjaxCursor}{\text{_}} ...and here is the accompanying css: .mathjaxCursor { font-weight: bold; background-color: red; } This setup results in the following display: ...

A Challenge with Session Variables in Internet Explorer 8 and Classic ASP

I run a website that has a stock management system with a table displaying stock and inventory information. When the "images" link is clicked, the Session variable for images switches between "show" and "hide" and then reloads the page with the updated va ...

Adding Information to a Material Design Card

Currently, I am delving into frontend development and honing my CSS skills. In my latest project, I have incorporated a mat card which can be viewed in the linked image https://i.sstatic.net/TEDcg.png. Below is an excerpt of my code: <div class=&quo ...

Halt the CSS transition on the preceding element

I tried to pause a CSS transition and came across a question with a solution that seems similar: Is there a way to pause CSS transition mid-way? However, I couldn't make it work for my code. I suspect the issue lies with the before element. What cou ...

Angular is failing to retrieve data from FS.readFile using promises

My goal is to utilize an Angular service to decide whether to call fs.readFile or fs.writeFile based on the button pressed, in order to explore the interaction between node and angular promises. Although I have managed to read and write files, I am facing ...

What is preventing my Express.js from running properly?

My express.js application stops running after reaching this point: node app.js info - socket.io started I'm looking for guidance on why this error occurs and how to resolve it. It seems like the issue lies within my app.js file, which I've inc ...

The functionality of jquery .serialize is not effective when used on forms that are generated dynamically

Currently, I am utilizing Java/Spring within a .jsp file. The issue arises when attempting to dynamically load a form (including form tags) from myForm.jsp into a div in myPage.jsp and making an ajax post call with the data. Upon using jQuery .serialize a ...

Troubleshooting Problems with Deploying Next Js on Firebase

I am currently working on a new Next Js application and have successfully deployed it on Vercel by linking the GitLab project. Now, I need to deploy the same project on Firebase. Here's what I have tried so far: - Ran firebase init This command gen ...

Here is a way to return a 400 response in `express.js` when the JSON request body is invalid

How can I make my application send a response with status code 400 instead of throwing an error if the request body contains invalid JSON? import express from 'express' app.use(express.urlencoded({ extended: false })) app.use(express.json()) ...

Learn how to efficiently process a data queue with AngularJS using Promises

Within my AngularJS application, I have a Service and multiple controllers running simultaneously. The app receives data updates from the server in JSON format through the Angular Service. To manage the vast amount of data, I need to queue it within the se ...

Unable to make a POST request to the GitHub v3 API

I'm attempting to generate a public gist using JavaScript without any authentication - all purely client-side. var gist = { "description": "test", "public": true, "files": { "test.txt": { "content": "contents" ...

Issue with PrimeFaces radiobutton styles not updating after being clicked programmatically

My setup includes a p:selectOneRadio constructed like this: <p:selectOneRadio id="positionRadio" value="#{employeeBean.empPosition}" converter="#{empPositionConverter}" layout="custom" required="true" requiredMessage="Please select ...

Entire body encompassing table

I am trying to create an HTML page with a table that spans the entire body and displays scrollbars when needed for both horizontal and vertical scrolling. Here is my current styling for the table: table { box-shadow: inset 0 0 10px #000; position: ...