Search code examples
javascriptjqueryhtml-tablecelllines

jQuery : multi lines operations on an html table


I have an html table like that :

time | time_diff
12:01| 
12:21|
12:31|

how could I calculate time_diff using Javascript (with or without jQuery) so my table looks like :

time | time_diff
12:01| 20
12:21| 10
12:31| 

I'm basically wondering how I can achieve multi lines operations on an html table?


Solution

  • Maybe something like this:

    $('table tbody tr').each(function () {
    
        var $row = $(this),
            $nextRow = $row.next();
    
        if ($nextRow.length) {
            this.cells[1].innerHTML = timeDiff($nextRow.find('td').text(), $row.find('td').text());
        }
    });
    
    function timeDiff(t1, t2) {
        t1 = t1.split(':');
        t2 = t2.split(':');
        var diff = (t1[0] * 60 + +t1[1]) - (t2[0] * 60 + +t2[1]),
            hours = Math.floor(diff / 60),
            minutes = (diff - hours * 60) + '';
        return hours + ':' + (minutes.length == 1 ? '0' + minutes : minutes);
    }
    

    Demo: http://jsfiddle.net/vJNa4/1/