I'm needing jQuery to automatically give me the sum of the time in the input fields. I would like it to show the total in another input field with the value set to the total time. Example below.
input 1: 18:30 //format mm:ss
input 2: 3:00
input 3: 0:00
input 4: 0:30
------------------
Total: 22:00
Something like this might help u mate :) Before u copy paste the code try to understand what happens behind the scenes.
HTML
<input value="1:45" size="5">Time 1
<input value="1:30" size="5">Time 2
<input value="1:32" size="5">Time 3
<input value="5:30" size="5">Time 4
<button id="addTimes">Add times</button>
<br>Result<span id="timeSum"></span>
Script
Number.prototype.padDigit = function () {
return (this < 10) ? '0' + this : this;
}
$("#addTimes").on('click', function () {
var t1 = "00:00";
var mins = 0;
var hrs = 0;
$('input').each(function () {
t1 = t1.split(':');
var t2 = $(this).val().split(':');
mins = Number(t1[1]) + Number(t2[1]);
minhrs = Math.floor(parseInt(mins / 60));
hrs = Number(t1[0]) + Number(t2[0]) + minhrs;
mins = mins % 60;
t1 = hrs.padDigit() + ':' + mins.padDigit()
});
$('#timeSum').text(t1);
});
Fiddle
FYI
split()
ParseInt
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With