skyline33 skyline33 - 1 year ago 61
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

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")

Answer Source

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")

#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=""></script>
<script src=""></script>

<table id="table">
      <th>Split 1</th>
      <th>Split 2</th>
      <th>Split 3</th>
      <th>Total Time</th>
      <td>(total time)</td>
      <td>(total time)</td>
      <td>(total time)</td>