Switching Nested Table Columns - HTML, jQuery Skills

My experience with jQuery is still growing, but I'm well-versed in HTML and CSS.

Currently, I am tasked with developing a new report featuring a nested table displaying quarterly results. You can view a sample of the Quarterly Report here. When a user clicks on the image next to the Q1 or Q2 table row, my goal is for the Week (wk1 - wkn) columns to toggle visibility as needed. Furthermore, when week columns are hidden, I aim for the Quarterly column(s) to collapse and dynamically display the sum of the hidden weeks (wk1 - wkn). While most of the code has been borrowed from other sources, I have yet to find one that collapses and sums nested columns.

Thank you in advance for your assistance!

$(document).ready(function () {
 
 var mImg = "http://t1.gstatic.com/images?q=tbn:1PS9x2Ho4LHpaM:http://www.unesco.org/ulis/imag/minus.png";
 var pImg = "http://t3.gstatic.com/images?q=tbn:4TZreCjs_a1eDM:http://www.venice.coe.int/images/plus.png";

     var sum1 = 0;
     $('tr').find('.combat1').each(function () {
         var combat1 = $(this).text();
         if (!isNaN(combat1) && combat1.length !== 0) {
             sum1 += parseFloat(combat1);
         }
     });
     var sum2 = 0;
     $('tr').find('.combat2').each(function () {
         var combat2 = $(this).text();
         if (!isNaN(combat2) && combat2.length !== 0) {
             sum2 += parseFloat(combat2);
         }
     });
     var sum3 = 0;
     $('tr').find('.combat3').each(function () {
         var combat3 = $(this).text();
         if (!isNaN(combat3) && combat3.length !== 0) {
             sum3 += parseFloat(combat3);
         }
     });

     $('.total-combat1').html(sum1);
     $('.total-combat2').html(sum2);
     $('.total-combat3').html(sum3);
     
     $('.header').click(function() {
                //$('td:nth-child(2)').hide();
                // if your table has header(th), use this
                $('td:nth-child(2),th:nth-child(2)').toggle();
            });
            
 });
body {
    background: #80dfff;
    color: #d5d4d4;
    font-family: Helvetica, Arial, sans-serif;
    font-size: 12px;
    margin: 0;
    overflow-x: auto;
    padding: 30px;
}
table {
    background: white;
    border-collapse: collapse;
    border: 1px #393939 solid;
    color: black;
    margin: 1em 1em 1em 0;
}
thead {
    border-collapse: collapse;
    color: black;
}
th, td {
    border: 1px #aaa solid;
    padding: 0.2em;
}
<table>
    <thead>
    <tr><th colspan=8>2015</th></tr>
    <tr><th colspan=4 class="header">Q1 
    <img src="http://t1.gstatic.com/images?q=tbn:1PS9x2Ho4LHpaM:http://www.unesco.org/ulis/imag/minus.png" />
        </th>
        <th colspan=3 class="header">Q2 
    <img src="http://t1.gstatic.com/images?q=tbn:1PS9x2Ho4LHpaM:http://www.unesco.org/ulis/imag/minus.png" />
       </th>
       
        <th></th>
    </tr>
        <tr>
            <th>WK1</th>
            <th>WK2</th>
            <th>WK3</th>
            <th>WK4</th>
            
            <th>WK1</th>
            <th>WK2</th>
            <th>WK3</th>
            <th>Total</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td class="combat1">8170</td>
            <td class="combat1">6504</td>
            <td class="combat1">6050</td>
            <td class="combat1">6050</td>
            
            <td class="combat1">7050</td>
            <td class="combat1">7050</td>
            <td class="combat1">7050</td>
            
            <td class="total-combat1"></td>
        </tr>
        <tr>
            <td class="combat2">8500</td>
            <td class="combat2">10200</td>
            <td class="combat2">7650</td>
            <td class="combat2">7650</td>
            
            <td class="combat2">8650</td>
            <td class="combat2">8650</td>
            <td class="combat2">8650</td>
            
            <td class="total-combat2"></td>
        </tr>
        <tr>
            <td class="combat3">9185</td>
            <td class="combat3">5515</td>
            <td class="combat3">6185</td>
            <td class="combat3">7185</td>
            
            <td class="combat3">9185</td>
            <td class="combat3">9185</td>
            <td class="combat3">9185</td>
            
            <td class="total-combat3"></td>
        </tr>
    </tbody>
</table>

Answer №1

If you want to alternate the visibility of Q1 or Q2, you can adjust the header click event to achieve the desired effect shown in the code below.

The challenge lies in selecting all the cells you're interested in and then toggling their visibility.

One method is to narrow down the selected cells using jQuery's :lt and :gt selectors along with the css function.

Answer №2

After analyzing your intentions, let me clarify: you are attempting to toggle the display of columns under a specific header column, like Q1, upon clicking on the header itself. If this is indeed the case, here is the modified code I came up with. I made enhancements by incorporating nested tables within the main table structure to segregate and manage the two sets of information effectively, enabling easy selection for toggling using jQuery.

$(document).ready(function() {

  var minusImage = "http://t1.gstatic.com/images?q=tbn:1PS9x2Ho4LHpaM:http://www.unesco.org/ulis/imag/minus.png";
  var plusImage = "http://t3.gstatic.com/images?q=tbn:4TZreCjs_a1eDM:http://www.venice.coe.int/images/plus.png";

  var sum1 = 0;
  $('tr').find('.combat1').each(function() {
    var combat1 = $(this).text();
    if (!isNaN(combat1) && combat1.length !== 0) {
      sum1 += parseFloat(combat1);
    }
  });
  var sum2 = 0;
  $('tr').find('.combat2').each(function() {
    var combat2 = $(this).text();
    if (!isNaN(combat2) && combat2.length !== 0) {
      sum2 += parseFloat(combat2);
    }
  });
  var sum3 = 0;
  $('tr').find('.combat3').each(function() {
    var combat3 = $(this).text();
    if (!isNaN(combat3) && combat3.length !== 0) {
      sum3 += parseFloat(combat3);
    }
  });


  $('.header-1').click(function() {
    $("#table1").toggle();
  });

  $('.header-2').click(function() {
    $("#table2").toggle();
  });

});
body {
  color: #d5d4d4;
  font-family: Helvetica, Arial, sans-serif;
  font-size: 12px;
  margin: 0;
  overflow-x: auto;
  padding: 30px;
}
table {
  background: white;
  border-collapse: collapse;
  border: 1px #393939 solid;
  color: black;
  margin: 0;
  padding: 0;
}
thead {
  border-collapse: collapse;
  color: black;
}
th,
td,
tr {
  border: 1px #aaa solid;
  padding: 0;
}
td.combat {
  padding: 0.2em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<table id="myTable">
  <thead>
    <tr>
      <th colspan=2>2015</th>
    </tr>
    <tr>
      <th class="header-1">Q1
        <img src="http://t1.gstatic.com/images?q=tbn:1PS9x2Ho4LHpaM:http://www.unesco.org/ulis/imag/minus.png" />
      </th>
      <th class="header-2">Q2
        <img src="http://t1.gstatic.com/images?q=tbn:1PS9x2Ho4LHpaM:http://www.unesco.org/ulis/imag/minus.png" />
      </th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>
        <table id="table1">
          <tr>
            <th>WK1</th>
            <th>WK2</th>
            <th>WK3</th>
            <th>WK4</th>
          </tr>
          <tr>
            <td class="combat combat1">8170</td>
            <td class="combat combat1">6504</td>
            <td class="combat combat1">6050</td>
            <td class="combat combat1">6050</td>
          </tr>

          <tr>
            <td class="combat combat1">8170</td>
            <td class="combat combat1">6504</td>
            <td class="combat combat1">6050</td>
            <td class="combat combat1">6050</td>
          </tr>
        </table>
      </td>
      <td>
        <table id="table2">
          <tr>
            <th>WK1</th>
            <th>WK2</th>
            <th>WK3</th>
          </tr>
          <tr>
            <td class="combat combat2">7050</td>
            <td class="combat combat2">7050</td>
            <td class="combat combat2">7050</td>
          </tr>
          <tr>
            <td class="combat combat2">7050</td>
            <td class="combat combat2">7050</td>
            <td class="combat combat2">7050</td>
          </tr>
        </table>
      </td>
      <td>
        <table>
          <tr>
            <td></td>
          </tr>
          <tr>
            <td></td>
          </tr>
          <tr>
            <td></td>
          </tr>
        </table>
      </td>
    </tr>
  </tbody>
</table>

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

The functionality of the React Router DOM seems to be malfunctioning

I am facing an issue with running a program on my computer while it runs successfully on other PCs. When I try to run this program, I encounter the following error message. Any help in fixing this would be greatly appreciated... index.js import React, {C ...

Encountering a `Syntax Error` in a Jade view

I am attempting to create a basic chat application using the simple jade view engine with express. Upon running my app, I encountered a syntax error in the following view code, even though it seems quite straightforward. extends layout block scrip ...

Text wrapping over in 5 column design using Bootstrap

After building a simple webpage with Bootstrap 5, I've run into an issue where the text in the columns overlaps. When the screen is at its full size, everything looks good. But as I start to reduce the size of the screen, the text gets smaller until t ...

Can the mDNS string received through webRTC be decoded to retrieve a user's IP address?

After doing some thorough research, I came across this insightful response from a different Stack Overflow question. The problem at hand involves retrieving an mDNS string, which looks like this: abcd1234-1e1e-1e1e-1e1e-abcd1a2bc3de.local I have a genuin ...

transferring information between two html pages using javascript

Although this question has been raised multiple times, I have gone through the answers and attempted various solutions, however, my code is still not functioning correctly. Below are my working files : my_app -index.html -task1 -index.html I ...

Struggling to find and interact with a button element, however Selenium Webdriver is throwing a NoSuchElementException

After experimenting with various selectors and attributes in an attempt to target and click a sign-up button on a website's homepage, I have been unsuccessful. The website in question can be found at: When the webdriver is initiated, all actions are ...

Transitioning Dropdowns in Angular UI Bootstrap

Hello everyone, I am completely new to both Stack Overflow and AngularJS. I'm attempting to incorporate a fade-in animation into my dropdown (using UI Bootstrap's dropdown directive) without success. This issue is quite similar to the following ...

Is there a simple way to transfer all the form data to a new popup window using javascript?

I'm looking to create a printer-friendly version of a form in a new popup window. I'm wondering if there is a simple way to pass all of the form data to the popup, potentially by passing the form itself. Any advice on how to achieve this would be ...

Error in MVC Ajax with Int32 data type

Whenever I attempt to make an Ajax post request to my controller, I am faced with the following error message: The parameters dictionary includes a null entry for parameter 'id' of non-nullable type 'System.Int32' for method &a ...

Parsing Problem---Is there a Parsing Error?

My code includes a function that calculates the total of cells and then displays it in a textbox: function UpdateTotal() { var total = parseFloat('0.0'); $("#<%= gvParts.ClientID %>").find("tr").not(".tblResultsHeader").each(funct ...

Calculating minutes per hour during a specific date range using JavaScript

What is the method to create an array representing minute counts per hour within a specified date range? If we have the following dates: const initial = new Date('2019-04-04 12:14'); const final = new Date('2019-04-04 16:21'); How ca ...

What is the mechanism behind making a Promise appear synchronous when using a Proxy in JavaScript?

const handler: ProxyHandler<any> = { get: (target: Promise<any>, prop: string, receiver: any) => { return target.then((o) => { return o[prop].apply(o); }); }, }; return new Proxy(obj, handler) ...

Incorporate Add to Homescreen functionality into your Angular 4 Project using JavaScript

Currently I am in the beginning stages of learning Angular development. One of my assignments involves integrating the add to homescreen jQuery plugin into one of my pages. This is my attempt at implementing it in my home.component.ts file: ngAfterViewIn ...

Creating a fixed container with CSS in Internet Explorer 6

#fixed { border:1px solid red; height:100px; left:50%; margin-left:-500px; position:fixed; top:0; width:1000px; } Can anyone help me ensure that this element displays correctly in IE6? The div is the first element directly unde ...

"Dragging and dropping may not always perfectly align with the position of the droppable div that is

When attempting to drag and drop three images into a droppable div, I encountered an issue where the images were not perfectly positioned within the div. This problem seemed to be related to the positioning of the droppable div itself. Specifically, when s ...

jQuery SlideDown Navigation

Is there a way to implement jQuery code that will display dropdown menu options when the Trials link is clicked? Update: jQuery(document).ready(function () { $("a[href='http://sheep.local/cms/trials']").click(function(e){ e.prevent ...

Issues encountered during transition of HTML document to XML through VBA web scraping when attempting to click on a button

I am currently working on a project that involves using an MSHTML.HTMLDocument code to extract data from a specific webpage. The process involves the following steps: Opening the webpage at "https://www.ksestocks.com/HistoryHighLow" Entering a value ...

Using JQUERY for navigating through pages in a REST API while utilizing deferred functionality

I am utilizing a REST API in jSON format to fetch records. My Approach The REST API retrieves records in jSON format. Initially, I retrieve the top 6 records, along with an additional jSON node containing a forward paging URL. This URL is assigned t ...

Doing a simple HTTP GET request with RxJS does not do anything

I'm encountering an issue with my code: export class Test { constructor(private http: Http) {} logResponse(): Observable<any> { return this.http.get('http://google.com') .do(data => console.log("All: " + JSON.stringify(dat ...

The Google Docs viewer is displaying an empty screen

I have been utilizing the Google Docs viewer on my website: <div class="embed-r embed-responsive-a"> <iframe class="embed-responsive-it" src="https://docs.google.com/viewer?embedded=true&amp;url=http://LINK.PDF"></iframe> </div& ...