Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery sum of total time in input fields

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
like image 807
Nathan Brown Avatar asked Sep 04 '25 16:09

Nathan Brown


1 Answers

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

like image 112
Outlooker Avatar answered Sep 07 '25 18:09

Outlooker