Question

How can I hide a detail row when I show another one?

Answer and Explanation

You can achieve this using HTML, CSS, and JavaScript (or jQuery for simpler syntax). The basic idea is to use JavaScript to toggle the visibility of detail rows, ensuring only one is visible at a time. Here’s a breakdown:

1. HTML Structure:

- Your main table should have rows, and each detail row should be placed immediately after its corresponding main row. Assign a unique class (e.g., detail-row) to the detail rows, and an ID to each main row that corresponds to its detail row.

2. CSS Styling (Initial State):

- Initially, all detail rows should be hidden using CSS. This ensures that when the page loads, no detail rows are visible until a user clicks on the main row.

3. JavaScript Logic:

- When a main row is clicked, the JavaScript function should first hide all other visible detail rows, and then show the detail row associated with the clicked main row.

4. Example Code (JavaScript):

document.addEventListener("DOMContentLoaded", function() {
  const mainRows = document.querySelectorAll(".main-row");

  mainRows.forEach(row => {
    row.addEventListener("click", function() {
      const detailRowId = this.getAttribute("data-detail-row");
      const detailRow = document.getElementById(detailRowId);

      // Hide all other detail rows
      document.querySelectorAll(".detail-row").forEach(dr => {
        if (dr !== detailRow) {
          dr.classList.add("hidden");
        }
      });

      // Toggle the clicked detail row
      detailRow.classList.toggle("hidden");
    });
  });
});

5. Example HTML:

<table>
  <tr class="main-row" data-detail-row="detail-1"><td>Main Row 1</td></tr>
  <tr class="detail-row hidden" id="detail-1"><td>Detail Row 1</td></tr>
  <tr class="main-row" data-detail-row="detail-2"><td>Main Row 2</td></tr>
  <tr class="detail-row hidden" id="detail-2"><td>Detail Row 2</td></tr>
</table>

6. Example CSS:

.hidden {
  display: none;
}

By implementing this approach, you can ensure that only one detail row is visible at any given time, providing a cleaner and more user-friendly interface. Remember to adjust the class and ID names to match your specific HTML structure.

More questions