简体   繁体   中英

Dynamically selecting column from a html table using jQuery

I have a sample fiddle here which contains a html table with print button. I am printing that whole table as,

function printpage() {
    var data = '<table border="1" cellspacing="0"><tr><td colspan="4">Sample Report</td></tr>' + document.getElementsByTagName('table')[0].innerHTML + '</table>';
    data += '<br/><button onclick="window.print()"  class="noprint">Print the Report</button>';
    data += '<style type="text/css" media="print"> .noprint {visibility: hidden;} </style>';
    myWindow = window.open('', '', 'width=800,height=600');
    myWindow.innerWidth = screen.width;
    myWindow.innerHeight = screen.height;
    myWindow.screenX = 0;
    myWindow.screenY = 0;
    myWindow.document.body.innerHTML = data;
    myWindow.focus();
}

But I want to include only the columns containing the non zero values in print preview, ie something like as follows:

在此输入图像描述

How it is possible?

If I understood correctly, you don't need to remove all cells with 0 values, only those columns where all values are 0. In your print function add this jquery snippet:

var printableTable = $("table").clone();
var columnLen = printableTable.find("tr:nth-child(1)").find("th").size();

for(var i=1; i<=columnLen; i++)
{
    var sum = 0;
    printableTable.find("tr td:nth-child("+i+")").each(function() 
    { 
        var nr = Number($(this).html());
        sum += nr;
    });

    if (sum == 0)
    {
        printableTable.find("tr th:nth-child("+i+")").each(function() {
            $(this).hide();
        });

        printableTable.find("tr td:nth-child("+i+")").each(function() {
            $(this).hide();
        });
    }
}

Than use: printableTable.html() instead of document.getElementsByTagName('table')[0].innerHTML

Working demo: http://jsfiddle.net/er144/84tgF/

Well first of all we have to clone that table, and find each td with 0 value.

var table = $("table").clone();
table.find("td").each(function(){
    if(!parseInt($(this).text())){
        $(this).remove();
    }
});

Than we have to remove each td if it's value is 0 and append the cloned table.

var data = '<table border="1" cellspacing="0"><tr><td colspan="4">Sample Report</td></tr>' + table.html() + '</table>';

Here is the updated fiddle http://jsfiddle.net/4d3jj/13/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM