Removing columns from a <table> via Javascript

Asked

Viewed 1,265 times

3

My web page is powered by database data and has a report format, with data inserted into an html table. The point is that the database has tables with many columns, which sometimes make the page very large by replicating the structure of the table within the page and consequently prevent printing from falling on paper.

I developed a method in javascript/jquery, responsible for hiding columns until they fill a predetermined space. For example, I can force the table to be 1500pixels wide, so the method eliminates columns until the table occupies this space.

However, it does not happen well... because in the beginning, the columns will be hidden and the table width will decrease, but after a while, the columns will be removed but the table continues to occupy the same size, because the columns will increase in width.

if(dimensao() == false){
                wt = document.getElementById('tabela').offsetWidth;
                col = document.getElementById('tabela').rows[0].cells.length;
                aux = 0;
                for(col;col>=2;col--){
                    if(wt>1500){
                        $('td:nth-child(' + col + ')').hide();
                        //alert('Coluna ' + col + ' Removida! - Largura : ' + wt);
                        wt = document.getElementById('tabela').offsetWidth;
                        aux++;
                    }
                }
                alert(aux + ' Colunas tiveram de ser removidas!.');
            }
        });

I wonder, how to hide the columns and prevent the remaining columns from increasing their own width, thus making the table decrease its length.

  • And can you erase columns inexcusably? or have columns to "keep"? I suggest having the column inside a wrapper and giving an overflow: scroll. Then take out columns until the width of the table is less than or equal to the wrapper.

1 answer

3


You can keep the table with width:100% in css and fix the minimum width of columns with min-width:25% for example.

When I handled this, I calculated the width of the column with the amount of columns being displayed:

var q = Math.round($("table").find("td").length / $("table tr").length) + 1;
var y = $(".table").outerWidth() - 160;
var l = Math.round(y / q);
$("table tr td").css("width",l);
$("table td").css("width",y);

First discovery q, dividing the tds for each row of the table and adding 1 because the first column was a TH.

Then I remove the width of the TH, which is fixed.

Then I divide the remaining size (which in your case I imagine is 100%) by tds of the line.

Then I apply this value as width in each td.

Sounds complicated but I don’t think you’d even need to use all this.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.