MTplus MTplus - 3 years ago 125
Javascript Question

display correct age depending on date value

I have a table which have a tbody and x number of rows containing persons and their ages like this..

<tbody>

<tr>
<td class="number">4</td>
<td class="name">Name</td>
<td class="age" data-date="2004-11-22 00:00:00">13</td>
</tr>
<tr>
<td class="number">5</td>
<td class="name">Name</td>
<td class="age" data-date="2003-11-22 00:00:00">14</td>
</tr>


I would like to display the correct age of all persons, but since this depends on the current date I'm thinking of entering the birthdate instead. But I still want to display the actual age of the player. How can I use a jQuery script that iterate all rows of the table and depending on the data-date value display the actual age in the corresponding td cell?

Answer Source

$('.age').each(function(i, e) {
  var now = new Date();
  var date = new Date(e.dataset.date);
  $(this).html(now.getFullYear() - date.getFullYear());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tbody>
    <tr>
      <td class="number">4</td>
      <td class="name">Name</td>
      <td class="age" data-date="2004-11-22 00:00:00"></td>
    </tr>
    <tr>
      <td class="number">5</td>
      <td class="name">Name</td>
      <td class="age" data-date="2003-11-22 00:00:00"></td>
    </tr>
  </tbody>
</table>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download