J.Jenke J.Jenke - 3 months ago 9
jQuery Question

addClass to <tr> depence of <td> value with JQuery

Bootstrap offers a .danger Class. I want to add this Class if the last td value is >= 0.
My Table look similiar to this one:

<table>
<thead>
<tr>
<th>#</th>
<th>Timestamp</th>
<th>Failures</th>
</tr>
</thead>
<tbody>
<tr>
<th>1</th>
<td>date</td>
<td>0</td>
</tr>
<tr>
<th>2</th>
<td>date</td>
<td>2</td>
</tr>
</tbody>




My solution:

$(document).ready(function () {
$("table tbody tr").each(function () {
var cell = $(this).find("td:last-child").text();

if ($(this).val()>='0') tr.addClass('danger');
else tr.removeClass('danger');
}
});
})


I think the problem is to get the value from the td. Or JQuery need a Class in the td permanently written and change form that one the Class.

Answer

Changes

  1. You need to use current element i.e. this in place of tr
  2. Use .text() to get the text as TD element doesn't have value properties
  3. For numerical comparison convert the text into appropriate date type. Here in example I have use parseInt().

Code

$("table tbody tr").each(function() {

   //Read text then it to number
   var cell = parseInt($(this).find("td:last").text(), 10);
   if (cell > 0) {
       $(this).addClass('danger'); //use current element
   } else {
       $(this).removeClass('danger'); //use current element
   }

});

$(document).ready(function() {
  $("table tbody tr").each(function() {

    //Parse text to number
    var cell = parseInt($(this).find("td:last").text(), 10);
    if (cell > 0)
      $(this).addClass('danger'); //use context selector this
    else
      $(this).removeClass('danger'); //use context selector this

  });
})
.danger {
  color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th>#</th>
      <th>Timestamp</th>
      <th>Failures</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>1</th>
      <td>date</td>
      <td>0</td>
    </tr>
    <tr>
      <th>2</th>
      <td>date</td>
      <td>2</td>
    </tr>
  </tbody>

Comments