skyline33 skyline33 - 3 months ago 10
jQuery Question

Iterate rows values of a time and add

I got dynamic table that gets data through ajax and so it grows and grows, im using a code that works perfectly for only a row but not multiple rows, example here http://jsfiddle.net/47uzgx9a/

You can see that the first row is perfect but the second and third row is not, the time it outputs is just the same as row 1 "01:54.397" and we need row 2 to be "01:54.610" and row 3 to be "01:54.730"

js code

var sp1 = $('#table tr td:nth-child(2)').text()
var sp2 = $('#table tr td:nth-child(3)').text()
var sp3 = $('#table tr td:nth-child(4)').text()
var1 = moment(sp1, "mm:ss.SSS") + moment(sp2, "mm:ss.SSS") + moment(sp3,"mm:ss.SSS")
$('td:nth-child(5)').html(moment(var1).format("mm:ss.SSS"));

Answer

You must iterate through each row and set the corresponding total to corresponding td

$('#table tr').each(function(){
var sp1 = $(this).find('td:nth-child(2)').text()
var sp2 = $(this).find('td:nth-child(3)').text()
var sp3 = $(this).find('td:nth-child(4)').text()
var1 = moment(sp1, "mm:ss.SSS") + moment(sp2, "mm:ss.SSS") + moment(sp3, "mm:ss.SSS")

 $(this).find('td:nth-child(5)').html(moment(var1).format("mm:ss.SSS"));
 });
#table {
	margin: 60px auto;
	font-family: "Lucida Sans Unicode", "Lucida Grande", Sans-Serif;
    font-size: 14px;
    width: 600px;
    table-layout: fixed;
    text-align: left;
    border-collapse: collapse;
}

#table th {
    font-size: 15px;
    font-weight: normal;
    background: #b9c9fe;
    border-top: 4px solid #aabcfe;
    border-bottom: 1px solid #fff;
    color: #039;
    padding: 8px;
}

#table td {
    background: #e8edff;
    border-bottom: 1px solid #fff;
    color: #669;
    border-top: 1px solid transparent;
    padding: 8px;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>

<table id="table">
  <thead>
    <tr>
      <th>Lap</th>
      <th>Split 1</th>
      <th>Split 2</th>
      <th>Split 3</th>
      <th>Total Time</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>0:31.110</td>
      <td>0:50.490</td>
      <td>0:32.797</td>
      <td>(total time)</td>
    </tr>
     <tr>
      <td>2</td>
      <td>0:31.300</td>
      <td>0:50.600</td>
      <td>0:32.710</td>
      <td>(total time)</td>
    </tr>
     <tr>
      <td>3</td>
      <td>0:31.500</td>
      <td>0:50.400</td>
      <td>0:32.830</td>
      <td>(total time)</td>
    </tr>
  </tbody>
</table>

Comments