Delete the designated column from the table

I am having difficulty with hiding and showing table columns using checkboxes. I need to eliminate the Mars column (in bold) along with its corresponding data (also in bold).

Once the Mars column is removed, I want the Venus column and its data values to be centered in the table.

Check out the example here: http://jsfiddle.net/bL44n3aj/3/

After removing the Mars column, this is the desired output: http://jsfiddle.net/2Lcsc2go/

This is my CSS and HTML code:

td{
  border:1px solid #000;
  
}
th{
  border:1px solid red;
  font-weight:normal !important;
}

tr.sub-header th{
  text-align:center !important;
   border:1px solid blue !important;
   font-weight:bold !important;
}

tr.sub-header-value td{
  text-align:center !important;
  font-weight:bold !important;
}
<table width="80%">
  <tr>
  <th>Produced</th>
    <th>Sold</th>
    <th>Produced</th>
    <th>Sold</th>
  
    </tr>
  <tr class="sub-header">
    <th colspan="2">Mars</th>
    <th colspan="2" scope="colgroup">Venus</th>
  </tr>
  <tr>
   <td>50,000</td>
    <td>30,000</td>
    <td>100,000</td>
    <td>80,000</td>
  </tr>
  <tr class="sub-header-value">
     <td colspan="2">Mars data</td>
    <td colspan="2"> Venus data </td>
    
  </tr>
  
  <tr>
 
    <td>10,000</td>
    <td>5,000</td>
    <td>12,000</td>
    <td>9,000</td>
  </tr>
   <tr class="sub-header-value">
     <td colspan="2">Mars data</td>
    <td colspan="2">Venus data</td>
    
  </tr>
</table>

<input type="checkbox"> Remove Mars

Answer №1

This method may seem a bit unconventional. To improve its efficiency, consider assigning classes to each individual td element.

Using jQuery here - would you prefer a JavaScript alternative?

$(function(){
  var removed = false;
  $("#removeMars").click(function(){
    if (!removed) {
      $.each($("#t tr"), function(){
        var tds = $(this).find("th, td");
        if (tds.length == 2) {
          $(tds[1]).attr("colspan", "4");
          $(tds[0]).remove();
        }
      })
      removed = true;
    }
  })
})
td{
  border:1px solid #000;
  
}
th{
  border:1px solid red;
}

tr.sub-header th{
  text-align:center !important;
   border:1px solid blue !important;
   font-weight:bold !important;
}

tr.sub-header-value td{
  text-align:center !important;
  font-weight:bold !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="t" width="80%">
  <tr>
  <th>Produced</th>
    <th>Sold</th>
    <th>Produced</th>
    <th>Sold</th>
  
    </tr>
  <tr class="sub-header">
    <th colspan="2" >Mars</th>
    <th colspan="2" scope="colgroup">Venus</th>
  </tr>
  <tr>
   <td>50,000</td>
    <td>30,000</td>
    <td>100,000</td>
    <td>80,000</td>
  </tr>
  <tr class="sub-header-value">
     <td colspan="2">Mars data</td>
    <td colspan="2"> Venus data </td>
    
  </tr>
  
  <tr>
 
    <td>10,000</td>
    <td>5,000</td>
    <td>12,000</td>
    <td>9,000</td>
  </tr>
   <tr class="sub-header-value">
     <td colspan="2">Mars data</td>
    <td colspan="2">Venus data</td>
    
  </tr>
</table>
<input type="checkbox" id="removeMars"> Remove Mars

Answer №2

Here is the finalized Solution:

 $(function(){
  var eliminated = false;
 $("#removeMars").change(function(){
        if(this.checked) {
    if (!eliminated) {
      $.each($("#t tr"), function(){
        var tds = $(this).find("th, td");

        if (tds.length == 2) {
          $(tds[1]).attr("colspan", "4");
          $(tds[0]).hide();

        }
      })
      eliminated = true;
    }
    }
    else{
         $.each($("#t tr"), function(){
        var tds = $(this).find("th, td");

        if (tds.length == 2) {
          $(tds[1]).attr("colspan", "2");
          $(tds[0]).show();

        }
      })    
      eliminated = false;
    }

  })
})

Access this Fiddle link : http://jsfiddle.net/qLo60ux8/

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 extent of locally declared variables within a Vue component

Within this code snippet: <template> <div> <p v-for="prop in receivedPropsLocal" :key="prop.id" > {{prop}} </p> </div> </template> <script> export default ...

When the browser back button is clicked, conceal the current div and reveal the previously hidden div

I'm faced with a situation where my website consists of multiple pages which I've achieved by displaying and hiding divs within a single html file. The issue I'm encountering is that the browser's back and forward buttons aren't fu ...

Checking the correctness of an entered regex pattern and example

My form contains two textboxes - one for entering a regex pattern, and the other for inputting text. I am attempting to validate if the entered regex pattern matches with the input text. Check out my simple code snippet. Here's a demo of it in acti ...

Best Practices for Installing Webpack in a Client/Server Folder Structure

Working on a React Nodejs web application and in the process of figuring out how to bundle the frontend using webpack. This is how my project's structured: Where exactly do I need to install webpack and configure webpack.config.js? I've noticed ...

What is the best way to swap out the if else statement with a Ternary operator within a JavaScript function?

Is there a way to replace the if else statement in the function using a Ternary operator in JavaScript? private getProductName(productType: string): string { let productName = 'Product not found'; this.deal.packages.find(p => p.isSele ...

Personalize Autocomplete CSS based on the TextField input in React Material UI when a value is present

In my current project, I am utilizing React Material Autocomplete fields, which includes a nested TextField. I have successfully implemented standard styles for when the field is empty and only the label is visible, as well as different styles for hover ef ...

Retrieving data from MySQL using PHP and AJAX with radio button selection

How can I update my code to display data from the database when a radio button is clicked instead of using a drop-down box? Here is an example of my current radio button code: <Input type='Radio' Name='compcase' value='1'/& ...

Is there a way to automatically scroll to the bottom of a div when it first

Looking to enhance my application with a chat feature that automatically scrolls to the bottom of the chat page to display the latest messages. Utilizing VueJs: <template> <div id="app"> <div class="comments" ...

Ways to prevent modal from flickering during event changes

I'm struggling with a current issue and need help identifying the cause and finding a solution. The problem arises from having a nested array of Questions, where I display a Modal onClick to show Sub questions. However, when clicking on the Sub Quest ...

Issues with the panel's scroll bar functionality in an HTML document

I am currently working with Bootstrap HTML 5 where I have a panel containing a table. Although I have set scroll for the panel, the table is not adjusting properly within the panel and the scrollbar appears inactive. My goal is to ensure that each header c ...

What is the best approach for scaling @material-ui Skeleton in a grid row with variable heights?

I am working on creating a grid of Avatar images with a transition state where I want to show a skeleton representation of the image. To achieve this, I am using @material-ui/lab/Skeleton. The issue I'm facing is that since my images are set to autos ...

What steps can be taken to make the carousel inconsistent when relying on the assigned id in props?

I recently developed a slider with slots, but encountered an issue. The code for this component revolves around the use of IDs for each slide as prop, making it unnecessarily complex. I am convinced that there is a more straightforward way to achieve the s ...

Troubleshooting: Issue with NodeJS Mongoose async function not returning value

Having an ongoing issue with retrieving a value from my async functions in the mongoose service. The problem persists as it consistently returns undefined, leaving me puzzled about what's going wrong. Being new to this area, any assistance would be gr ...

Storing and updating object property values dynamically within a for...in loop in JavaScript

I am currently working on a Node application powered by express and I am looking to properly handle apostrophes within the incoming request body properties. However, I am not entirely convinced that my current approach is the most efficient solution. expo ...

How to generate PDF downloads with PHP using FPDF

I am attempting to create a PDF using FPDF in PHP. Here is my AJAX call: form = $('#caw_auto_form'); validator = form.validate(); data = form.serializeObject(); valid = validator.form(); //alert("here"); ajax('pos/pos_api.php',data,fun ...

Problems with the zoom functionality for images on canvas within Angular

Encountering a challenge with zooming in and out of an image displayed on canvas. The goal is to enable users to draw rectangles on the image, which is currently functioning well. However, implementing zoom functionality has presented the following issue: ...

Using Angular and Typescript to implement a switch case based on specific values

I am attempting to create a switch statement with two values. switch ({'a': val_a,'b': val_b}){ case ({'x','y'}): "some code here" break; } However, this approach is not functioning as expected. ...

Unlocking new possibilities with Passport.js - sharing tokens across multiple servers

Currently, I am utilizing passport.js and MongoDB to handle user login and postAPI authentications. However, every time I deploy my node server to a different AWS instance, I find myself having to go through the signup process, log in, and obtain a new tok ...

The automation script for Playwright/Puppeteer is having trouble properly handling `async...await` in a `for..loop` on the `/signup` page

Currently, I am faced with the challenge of automating rate-limit requests using a playwright automation script. The issue arises when the script keeps attempting to sign up with the email <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data ...

Decoding the enigma of addEventListener in Nuxt: Unveiling the "referenceError: window is not defined" issue

I am currently working on developing a hamburger menu, but I have encountered an error. The error message states: ReferenceError: window is not defined. The issue seems to be within the created section of the code. <script> export default { ...