Shashank
Shashank

Reputation: 31

How can I hide table column when all "td" in the column are empty?

My Table Looks likes this:

  <table id="mytable" width="500" border="1" cellspacing="0" cellpadding="0">
      <thead>
      <tr>
        <th>Col 1</th><th>Col 2</th><th>Col 3</th>
      </tr>
      </thead>
      <tbody>
      <tr>
        <td>abc</td>
        <td>abc</td>
        <td></td>
      </tr>
      <tr>
        <td>abc</td>
        <td>abc</td>
        <td></td>
      </tr>
      <tr>
        <td>abc</td>
        <td></td>
        <td></td>
      </tr>
      </tbody>
    </table>

I want to hide respective column if all td of that column are empty else that column should be shown.

Upvotes: 1

Views: 1923

Answers (4)

Nasser Ali Karimi
Nasser Ali Karimi

Reputation: 4663

If your column has specific data like '-' try this one:

    $('th').each(function(idx, el) {
    var check = !! $('tr').find('td:eq(' + idx + ')').filter(function() {

           //If your column has specific data like `'-'` try this one:
           return $(this).text() != '-'; 


        }).length;
        $('tr').find('td:eq(' + idx + '), th:eq(' + idx + ')').toggle( check );
    });

Upvotes: 0

Muhammed Shevil KP
Muhammed Shevil KP

Reputation: 1396

Try like this

$("#mytable tbody tr").each(function (index, element) {
    if ($(element).find("td").not(':empty').length == 0) {
        $(element).hide();
    }
});

Fiddle

Remove 4 from 4th row and run

Upvotes: 0

billyonecan
billyonecan

Reputation: 20250

One approach would be to loop over each th, use its index to reference the tds in the same column, check if they're all empty, and if they are, hide all th and td elements in that column.

/* loop over each th */
$('th').each(function(idx, el) {

    /* check every td in the same column, see if they contain any text */
    var check = !! $('tr').find('td:eq(' + idx + ')').filter(function() {
       return $.trim( $(this).text() ).length; 
    }).length;

    /* toggle the display of each th and td in this column, based on the check above */
    $('tr').find('td:eq(' + idx + '), th:eq(' + idx + ')').toggle( check );


});

Here's a fiddle

Upvotes: 4

Robert
Robert

Reputation: 3543

please try

$("#mytable td:empty" ).hide();
$("#mytable td:not(:empty)").show();

Source

Upvotes: 0

Related Questions