The solution is to substract the time the #total0
field represents from the time the #tbtotal
field represents. Then you calculate the new #total0
field, and add that time to #tbtotal
again. This way the time displayed in #tbtotal
is always correct.
The other question seemed to be how to do this for all rows, instead of just this one. You can use the this
keyword to figure out what element fired the change event. From there you can figure out what the other elements would be. For this purpose I renamed the fields to timefr0
and timeto0
, so they are equal length.
I took the liberty to convert all times to seconds, and manipulate them that way. The comments in the script should speak for themselfs.
function updateTotals() {
//Get num part of the id from current set
//Cheated a bit with the id names ;-)
var num = $(this).attr('id').substr( 6 );
//Get the time from each and every one of them
var tfrom = $('#timefr' + num ).val().split(':');
var tto = $('#timeto' + num ).val().split(':');
var currtotal = $('#total' + num ).val().split(':');
var grandtotal = $('#tbtotal').val().split(':');
//Convert to seconds and do the calculations the easy way
var diff = (tto[0] - tfrom[0]) * 3600 + (tto[1] - tfrom[1]) * 60;
var totalsec = currtotal[0] * 3600 + currtotal[1] * 60;
var grandtotalsec = grandtotal[0] * 3600 + grandtotal[1] * 60;
//If the result is negative, we can't do anything sensible. Use 0 instead.
if( diff < 0 ) {
diff = 0;
}
//Substract what we calculated last time
grandtotalsec -= totalsec;
//Then add the current diff
grandtotalsec += diff;
//Convert diff (or total) into human readable form
var hours = Math.floor( diff / 3600 );
diff = diff % 3600;
var minutes = Math.floor( diff / 60 );
hours = (hours < 10) ? "0" + hours.toString() : hours.toString();
minutes = (minutes < 10) ? "0" + minutes.toString() : minutes.toString();
//Convert grandtotal into human readable form
var grandtotalhours = Math.floor( grandtotalsec / 3600 );
grandtotalsec = grandtotalsec % 3600;
var grandtotalminutes = Math.floor( grandtotalsec / 60 );
grandtotalhours = (grandtotalhours < 10) ? "0" + grandtotalhours.toString() : grandtotalhours.toString();
grandtotalminutes = (grandtotalminutes < 10) ? "0" + grandtotalminutes.toString() : grandtotalminutes.toString();
//Put them in the fields
$( '#total' + num ).val( hours + ":" + minutes );
$( '#tbtotal' ).val( grandtotalhours + ":" + grandtotalminutes );
}
An example fiddle can be found here.