dedi wibisono
dedi wibisono

Reputation: 533

jQuery - Hide last child <td> from <table>

I want to hide if the hobby doesn't have value (empty). But if the hobby has value is still show. How to condition it? I try using jQuery.

$("tr:last-child td:last-child").css("font-weight","bold")

if($("tr:last-child td:last-child").length < 1){
	$("tr:last-child").hide()
}
table{
  border: 1px solid blue;
  padding: 4px 8px;
  margin:4px 0
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>Name</td>
    <td>John</td>
  </tr>
  <tr>
    <td>Hobby</td>
    <td>Sleeping</td>
  </tr>
</table>

<table>
  <tr>
    <td>Name</td>
    <td>Doe</td>
  </tr>
  <tr>
    <td>Hobby</td>
    <td></td>
  </tr>
</table>

Upvotes: 0

Views: 428

Answers (3)

flyingfox
flyingfox

Reputation: 13506

You need to use text() to get the text of td

$("tr:last-child td:last-child").each(function(index,element){
    $(element).css("font-weight","bold");
});
$("tr:last-child td:last-child").each(function(index,element){
    if($.trim($(element).text()).length == 0){
       $(element).parent().hide();
    }
});
table{
  border: 1px solid blue;
  padding: 4px 8px;
  margin:4px 0
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>Name</td>
    <td>John</td>
  </tr>
  <tr>
    <td>Hobby</td>
    <td>Sleeping</td>
  </tr>
</table>

<table>
  <tr>
    <td>Name</td>
    <td>Doe</td>
  </tr>
  <tr>
    <td>Hobby</td>
    <td></td>
  </tr>
</table>

Upvotes: 1

Andy
Andy

Reputation: 51

You can hide the .parent() tr if the .text() of the td is blank.

$("tr:last-child td:last-child").each(function(index, td) {
  if($(td).text() === ""){
    $(td).parent().hide();
  }
});
table {
  border: 1px solid blue;
  padding: 4px 8px;
  margin:4px 0
}
tr:last-child td:last-child {
  font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>Name</td>
    <td>John</td>
  </tr>
  <tr>
    <td>Hobby</td>
    <td>Sleeping</td>
  </tr>
</table>
<table>
  <tr>
    <td>Name</td>
    <td>Doe</td>
  </tr>
  <tr>
    <td>Hobby</td>
    <td></td>
  </tr>
</table>

Upvotes: 2

wang
wang

Reputation: 1780

change this:

if($("tr:last-child td:last-child").length < 1){
    $("tr:last-child").hide()
}

to:

if($("tr:last-child td:last-child").text().length < 1){
    $("tr:last-child").hide()
}

Upvotes: 0

Related Questions