Sanju Menon
Sanju Menon

Reputation: 729

Hide complete column if data is null or empty using jquery

I would like to hide the complete column including the heading if data is empty or null. I tried to do this with jquery, but iam not able to accomplish what iam trying. Basically iam getting some records in PHP. Some columns doesnt have data, so i dont need to show the empty data or data which is NULL. Can anyone guide me on whats the mistake iam making.

<html>

<head>
<title>Hide</title>
 <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.2.js"></script>
</head>

<body>

<table border="1" width="100%" id="mytable">
   <thead>
   <tr>
   <th>Head1</th>
   <th>Head2</th>
   <th>Head3</th>
   </thead>
   </tr>

<tr>
<td>aa</td>
<td></td>
<td>cc</td>
</tr>
<tr>
<td>aa</td>
<td></td>
<td>cc</td>
</tr>
<tr>
<td>aa</td>
<td></td>
<td>cc</td>
</tr>
</table>

</body>

</html>
<script type='text/javascript'>
$(window).load(function(){
$('#mytable > tbody  > tr td:empty').parent().hide()
if($td.text() == ''){
    $(this).hide();
    }
});

});

</script>

Upvotes: 1

Views: 3174

Answers (1)

Barmar
Barmar

Reputation: 781096

Your selector finds any empty cell in the table, and then it hides the entire row that contains it, since the parent of a td is the tr. You need to loop through the columns, and test whether all the cells in that column are empty. Then hide all the cells in that column.

$(document).ready(function() {
  var columns = $("#mytable > tbody > tr:first > td").length;
  for (var i = 0; i < columns; i++) {
    if ($("#mytable > tbody > tr > td:nth-child(" + i + ")").filter(function() {
      return $(this).text() != '';
    }).length == 0) {
      $("#mytable > tbody > tr > td:nth-child(" + i + "), #mytable > thead > tr > th:nth-child(" + i + ")").hide();
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table border="1" width="100%" id="mytable">
  <thead>
    <tr>
      <th>Head1</th>
      <th>Head2</th>
      <th>Head3</th>
    </tr>
  </thead>


  <tr>
    <td>aa</td>
    <td></td>
    <td>cc</td>
  </tr>
  <tr>
    <td>aa</td>
    <td></td>
    <td>cc</td>
  </tr>
  <tr>
    <td>aa</td>
    <td></td>
    <td>cc</td>
  </tr>
</table>

Upvotes: 4

Related Questions