How to Hide Columns in HTML Table

How to hide columns in HTML table?

You need to use Style Sheet for this purpose.

<td style="display:none;">

How to hide column in HTML table

I see that you use some classes like grossAmount, discount, gst and netAmount in the table header... That's a good thing.

It even would be better if those classes were added to the corresponding cells in each row. You could use those really easilly to show/hide the cells.

I achieved something way more complicated using something like 3 nested loops to show the cells based on the index of the header having a selected class.

I took the selected classes from the #To input, which is a coma separated list of words close to the classes needed to find the column indexes.

Note that it is far from optimal and efficient coding, but it works... And could be instructive to you. ;)

$("#save").on("click",function(){

// Get the selected classes
var classes = $("#To").val().replace(/\s+/g,"").split(",");

// Hide cells
$(".table thead tr:not(:first) th:not(:first-child)").hide();
$(".table tbody tr td:not(:first-child)").hide();

// Adjust thead first row colspans
$(".table thead tr:first th:not(:first)").attr("colspan",classes.length);

// For each classes selected
for(i=0;i<classes.length;i++){
//force 3 first letters to lowercase
var classToShow = classes[i].substr(0,3).toLowerCase() + classes[i].substr(3);

// For each element having the class
$("."+classToShow).each(function(){
var index = $(this).index();

// Show selected cells in the thead
$(".table thead tr:not(:first)").each(function(){
$(this).find("th").eq(index).show();
});

// Show selected cells in the tbody
$(".table tbody tr").each(function(){
$(this).find("td").eq(index).show();
});
});
}
});

$("#save").on("click",function(){    // Get the selected classes  var classes = $("#To").val().replace(/\s+/g,"").split(",");    // Hide cells  $(".table thead tr:not(:first) th:not(:first-child)").hide();  $(".table tbody tr td:not(:first-child)").hide();    // Adjust thead first row colspans  $(".table thead tr:first th:not(:first)").attr("colspan",classes.length);    // For each classes selected  for(i=0;i<classes.length;i++){    //force 3 first letters to lowercase    var classToShow = classes[i].substr(0,3).toLowerCase() + classes[i].substr(3);        // For each element having the class    $("."+classToShow).each(function(){      var index = $(this).index();            // Show selected cells in the thead      $(".table thead tr:not(:first)").each(function(){        $(this).find("th").eq(index).show();      });            // Show selected cells in the tbody      $(".table tbody tr").each(function(){        $(this).find("td").eq(index).show();      });    });  }});
// ======================= NOTHING CHANGED BELOW
$(".checkbox-menu").on("change", "input[type='checkbox']", function() { // this one to select multiple options as check box $(this).closest("li").toggleClass("active", this.checked); var sList = ""; $('input[type=checkbox]').each(function() { if (this.checked) { sList += $(this).val() + "," } });
$("#To").val(sList.slice(0, -1));});
$(document).on('click', '.allow-focus', function(e) { e.stopPropagation();});
var data = [{ "billdate": "2018-08-04", "outlet": "JAYANAGAR", "gross": 490465, "discount": 839, "GST": 28465, "amount": 518212 }, { "billdate": "2018-08-04", "outlet": "MALLESHWARAM", "gross": 99212, "discount": 0, "GST": 5567, "amount": 104801 }, { "billdate": "2018-08-04", "outlet": "KOLAR", "gross": 131349, "discount": 0, "GST": 6676, "amount": 138151 }, { "billdate": "2018-08-05", "outlet": "JAYANAGAR", "gross": 594466, "discount": 591, "GST": 34374, "amount": 628358 }, { "billdate": "2018-08-05", "outlet": "MALLESHWARAM", "gross": 109029, "discount": 0, "GST": 6062, "amount": 115113 }, { "billdate": "2018-08-05", "outlet": "KOLAR", "gross": 127449, "discount": 0, "GST": 6511, "amount": 134107 }, { "billdate": "2018-08-06", "outlet": "JAYANAGAR", "gross": 167811, "discount": 0, "GST": 9968, "amount": 177866 }, { "billdate": "2018-08-06", "outlet": "KOLAR", "gross": 62796, "discount": 0, "GST": 3257, "amount": 66095 }, { "billdate": "2018-08-07", "outlet": "JAYANAGAR", "gross": 267398, "discount": 268, "GST": 15898, "amount": 283124 }, { "billdate": "2018-08-07", "outlet": "MALLESHWARAM", "gross": 55381, "discount": 0, "GST": 3383, "amount": 58789 }, { "billdate": "2018-08-07", "outlet": "KOLAR", "gross": 64586, "discount": 6, "GST": 3285, "amount": 67886 }]
let formatData = function(data) { let billdates = []; let outlets = []; data.forEach(element => { if (billdates.indexOf(element.billdate) == -1) { billdates.push(element.billdate); } if (outlets.indexOf(element.outlet) == -1) { outlets.push(element.outlet); } }); return { data: data, billdates: billdates, outlets: outlets,
};};
let renderTable = function(data) { billdates = data.billdates; outlets = data.outlets; data = data.data; let tbl = document.getElementById("dailySales"); let table = document.createElement("table"); let thead = document.createElement("thead"); let headerRow = document.createElement("tr"); let th = document.createElement("th"); th.innerHTML = "BillDate"; th.classList.add("text-center"); headerRow.appendChild(th); let grandTotal = 0; let grandGross = 0; let grandDiscount = 0; let grandGst = 0; let outletWiseTotal = {}; let outletWiseGross = {}; let outletWiseDiscount = {}; let outletWiseGst = {}; th = document.createElement("th"); th.colSpan = 4; th.innerHTML = "Total"; th.classList.add("text-center"); headerRow.appendChild(th); outlets.forEach(element => {
th = document.createElement("th"); th.colSpan = 4; th.innerHTML = element; th.classList.add("text-center"); headerRow.appendChild(th);
outletWiseTotal[element] = 0; outletWiseGross[element] = 0; outletWiseDiscount[element] = 0; outletWiseGst[element] = 0; data.forEach(el => { if (el.outlet == element) { outletWiseTotal[element] += parseInt(el.amount); outletWiseGross[element] += parseInt(el.gross); outletWiseDiscount[element] += parseInt(el.discount); outletWiseGst[element] += parseInt(el.GST); } }); grandTotal += outletWiseTotal[element]; //calculating totals for Total column grandGross += outletWiseGross[element]; grandDiscount += outletWiseDiscount[element]; grandGst += outletWiseGst[element]; });
thead.appendChild(headerRow); headerRow = document.createElement("tr"); th = document.createElement("th"); th.innerHTML = ""; headerRow.appendChild(th);
for (i = 0; i < outlets.length + 1; i++) { //here i am making the header as col-span th = document.createElement("th"); th.innerHTML = "Discount"; th.classList.add("text-center"); th.classList.add("discount"); //adding class to column discount headerRow.appendChild(th);
th = document.createElement("th"); th.innerHTML = "GST"; th.classList.add("text-center"); th.classList.add("gst"); //adding class to column gst headerRow.appendChild(th);
th = document.createElement("th"); th.innerHTML = "Net Amount"; th.classList.add("text-center"); th.classList.add("netAmount"); //adding class to column Net Amount headerRow.appendChild(th);
th = document.createElement("th"); th.innerHTML = "Gross Amount"; th.classList.add("text-center"); th.classList.add("grossAmount"); //adding class to column Gross Amount headerRow.appendChild(th); }
headerRow.insertBefore(th, headerRow.children[1]); thead.appendChild(headerRow); table.appendChild(thead);
headerRow = document.createElement("tr"); td = document.createElement("th"); td.innerHTML = "Total"; td.classList.add("text-center"); headerRow.appendChild(td);
outlets.forEach(element => { // these are the table rows for each column td = document.createElement("th"); td.innerHTML = outletWiseGross[element].toLocaleString('en-IN'); td.classList.add("text-right"); headerRow.appendChild(td);
td = document.createElement("th"); td.innerHTML = outletWiseDiscount[element].toLocaleString('en-IN'); td.classList.add("text-right"); headerRow.appendChild(td);
td = document.createElement("th"); td.innerHTML = outletWiseGst[element].toLocaleString('en-IN'); td.classList.add("text-right"); headerRow.appendChild(td);
td = document.createElement("th"); td.innerHTML = outletWiseTotal[element].toLocaleString('en-IN'); td.classList.add("text-right"); headerRow.appendChild(td);

}); td = document.createElement("th"); td.innerHTML = grandTotal.toLocaleString('en-IN'); td.classList.add("text-right"); headerRow.insertBefore(td, headerRow.children[1]);
td = document.createElement("th"); td.innerHTML = grandGst.toLocaleString('en-IN'); td.classList.add("text-right"); headerRow.insertBefore(td, headerRow.children[1]);
td = document.createElement("th"); td.innerHTML = grandDiscount.toLocaleString('en-IN'); td.classList.add("text-right"); headerRow.insertBefore(td, headerRow.children[1]);
td = document.createElement("th"); td.innerHTML = grandGross.toLocaleString('en-IN'); td.classList.add("text-right"); headerRow.insertBefore(td, headerRow.children[1]);

thead.appendChild(headerRow); table.appendChild(thead);
let tbody = document.createElement("tbody"); billdates.forEach(element => { let row = document.createElement("tr"); td = document.createElement("td"); td.innerHTML = element; row.appendChild(td);
let total = 0; let totalGross = 0; let totalDiscount = 0; let totalGST = 0; outlets.forEach(outlet => { let ta = 0; let tg = 0; let tdi = 0; let tgst = 0; data.forEach(d => { if (d.billdate == element && d.outlet == outlet) { total += parseInt(d.amount); totalGross += parseInt(d.gross); totalDiscount += parseInt(d.discount); totalGST += parseInt(d.GST); ta = d.amount; tg = d.gross; tdi = d.discount; tgst = d.GST; } });
td = document.createElement("td"); td.innerHTML = tg.toLocaleString('en-IN'); td.classList.add("text-right"); row.appendChild(td);
td = document.createElement("td"); td.innerHTML = tdi.toLocaleString('en-IN'); td.classList.add("text-right"); row.appendChild(td);
td = document.createElement("td"); td.innerHTML = tgst.toLocaleString('en-IN'); td.classList.add("text-right"); row.appendChild(td);
td = document.createElement("td"); td.innerHTML = ta.toLocaleString('en-IN'); td.classList.add("text-right"); row.appendChild(td);



});

td = document.createElement("td"); td.innerHTML = total.toLocaleString('en-IN'); td.classList.add("text-right"); row.insertBefore(td, row.children[1]);
td = document.createElement("td"); td.innerHTML = totalGST.toLocaleString('en-IN'); td.classList.add("text-right"); row.insertBefore(td, row.children[1]);
td = document.createElement("td"); td.innerHTML = totalDiscount.toLocaleString('en-IN'); td.classList.add("text-right"); row.insertBefore(td, row.children[1]);


td = document.createElement("td"); td.innerHTML = totalGross.toLocaleString('en-IN'); td.classList.add("text-right"); row.insertBefore(td, row.children[1]);

tbody.appendChild(row); });
table.appendChild(tbody); tbl.innerHTML = ""; tbl.appendChild(table); table.classList.add("table"); table.classList.add("table-striped"); table.classList.add("table-bordered"); table.classList.add("table-hover");}let formatedData = formatData(data);renderTable(formatedData);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script><script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css"><div class="form-group col-xs-12 col-sm-12 col-md-4 col-lg-4"> <label for="subCategoryCode">Filter Data :</label> <div class="input-group"> <input type="text" class="form-control" aria-label="Text input with dropdown button" name="To" id="To" readonly> <div class="input-group-append"> <button class="btn btn-outline-secondary dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"></button> <ul class="dropdown-menu checkbox-menu allow-focus" aria-labelledby="dropdownMenu1">
<li><label> <input type="checkbox" value="Gross Amount"> Gross Amount </label></li>
<li><label> <input type="checkbox" value="Discount"> Discount </label></li>
<li><label> <input type="checkbox" value="GST"> GST </label></li> <li><label> <input type="checkbox" value="Net Amount"> Net Amount </label></li>

</ul> </div> <button type="button" class="commonButton" id="save"> <i class="fa fa-search"></i> Go </button> </div>
</div>

<div align="left" class="table table-responsive" id="commonDvScroll"> <table id="dailySales" class="maxWidthCommonTable"></table></div>

Html table hide columns best practice

I'm unsure of any types of practices particularly for this application. Also based on the information given so far.

The way you are doing it is not the best choice of going about this situation. You are taking data and putting them all in their own elements which not only clusters up HTML with unessessary elements (that are always hidden by CSS) but also can be more taxing then it has to on you and your viewers computer.

When you could be using the data attribute this is a great way to keep the information more consolated, less clutter, well organized, easy to read and manage. Also even when a element has the styling display:none it is still using the computer performance to render all of those elements.

You can read this thread that explains: Read More

How can i hide certain table column in a HTML table using CSS

You can indeed do this:

http://jsfiddle.net/nEQ6g/1/

*EDIT - From my knowledge nth-child and visability: hidden don't play nice together. For what you want, you'd need to use display: none; - based upon the code I've provided you.

CSS:

table{
border-collapse: collapse;
}

table tr td{
padding: 10px;
border: 1px solid #ccc;
-webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
-moz-box-sizing: border-box; /* Firefox, other Gecko */
box-sizing: border-box; /* Opera/IE 8+ */
}

table tr td:nth-child(n+4){
display: none;
}

HTML tables hide td cells

Tables should be used in certain scenarios - such as when you want to display tabular data - but they are often misused for page layout.

You can hide cells using visibility: hidden.

A side note, learn about html table elements such as thead, tbody and th. They will help structure your table with greater semantic meaning.

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table

table {  border-collapse: collapse;}
thead { background: yellow;}
th,td { border: 1px solid black;}
.hide { visibility: hidden; border: none;}
<div id="memtab">    <table>        <thead>          <tr>              <th>Head 1</th>              <th>Head 2</th>              <th>Head 3</th>              <th>Head 4</th>              <th>Head 5</th>          </tr>        </thead>        <tbody>            <tr>                <td>Display</td>                <td>Display</td>                <td>Display</td>                <td>Display</td>                <td>Display</td>            </tr>            <tr>                <td>Display</td>                <td>Display</td>                <td>Display</td>                <td>Display</td>                <td>Display</td>            </tr>            <tr>                <td>Display</td>                <td>Display</td>                <td>Display</td>                <td>Display</td>                <td>Display</td>            </tr>            <tr>                <td class="hide">Hide</td>                <td class="hide">Hide</td>                <td class="hide">Hide</td>                <td>Display</td>                <td>Display</td>            </tr>        </tbody>    </table></div>

Hide/Show Column in a HTML Table

I would like to do this without attaching a class to every td

Personally, I would go with the the class-on-each-td/th/col approach. Then you can switch columns on and off using a single write to className on the container, assuming style rules like:

table.hide1 .col1 { display: none; }
table.hide2 .col2 { display: none; }
...

This is going to be faster than any JS loop approach; for really long tables it can make a significant difference to responsiveness.

If you can get away with not supporting IE6, you could use adjacency selectors to avoid having to add the class attributes to tds. Or alternatively, if your concern is making the markup cleaner, you could add them from JavaScript automatically in an initialisation step.

How to hide columns in very long html table

To hide whole columns you can use a stacking definition:

// HTML
<table id="my-table" class="no-filter">
<tr>
<td class="column column1">c1</td>
<td class="column column2">c2</td>
<td class="column column3">c3</td>
</tr>
// etc x1000
</table>

// CSS
table td.column { display: none; } /* by default all columns are hidden */
table.no-filter td.column { display: block; } /* no-filter shows _all_ columns */
table.filter1 td.column1 { display: block; }
table.filter2 td.column2 { display: block; }
table.filter3 td.column3 { display: block; }

If you want to show just column1:

$("#my-table").removeClass("no-filter").addClass("filter1");

If you want to show column1 and column3:

$("#my-table").removeClass("no-filter").addClass("filter1").addClass("filter3");

If you need one-to-many filters

table.filter4 td.column4,
table.filter4 td.column5,
table.filter4 td.column99 { display: block; }
/* filter 4 shows column 4 5 and 99 */

Filters can overlap:

table.filter5 td.column5 { display: block; }
table.filter6 td.column5,
table.filter6 td.column6 { display: block; }

This assumes your filters are pre-defined and you know the filter-to-column mapping.

Minor note: I haven't tested this, there might be precedence issues. If the filters aren't applying properly change td.columnX to td.column.columnX



Related Topics



Leave a reply



Submit