user0129e021939232
user0129e021939232

Reputation: 6355

javascript iterate over input duration values and add together

Hi i have multiple duration values stored as hours minutes and seconds in html inputs as follows;

<input class="form-control user_actual_time" name="actual_time" type="text" value="30:30:00"> // (30 hours 30 mins 00 secs)
<input class="form-control user_actual_time" name="actual_time" type="text" value="1:30:00">// (1 hours 30 mins 00 secs)
<input class="form-control user_actual_time" name="actual_time" type="text" value="2:30:00">// (2 hours 30 mins 00 secs)
<input class="form-control user_actual_time" name="actual_time" type="text" value="3:30:00">  // (3 hours 30 mins 00 secs)  

I want to calculate the total duration and insert this into another input on the page. The above example should output a total of 38 hours.

However with the following code I get 3:30:0;

$("#calculate").on("click", function () {

    var findtotal = $('.user_actual_time');
    var sum = 0;
    $(findtotal).each(function () {
        var usertime = $(this).val();
        duration = usertime.split(":");
        console.log(duration[0] + duration[1] + duration[2]);
        console.table(duration);
        hours = parseInt(duration[0]);
        minutes = parseInt(duration[1]);
        seconds = parseInt(duration[2]);
        // Convert each 60 minutes to an hour
        if (minutes >= 60) {
            hours++;
            minutes -= 60;
        }


        // Convert each 60 seconds to a minute
        if (seconds >= 60) {
            minutes++;
            seconds -= 60;
        }

        var input = (hours+':'+minutes+':'+seconds);



    $('#total').val(input);
    });

});

I have a js fiddle below;

http://jsfiddle.net/8geour60/1/

Any ideas what I'm doing wrong and how I can calculate the total duration?

Upvotes: 0

Views: 94

Answers (1)

Kevin Simple
Kevin Simple

Reputation: 1213

mate, you are not updating the total sum, you need update it then output , ``check this:

  $("#calculate").on("click", function () {
var hours =0;
var minutes=0;
var seconds =0;
var findtotal = $('.user_actual_time');
var sum = 0;
$(findtotal).each(function () {
    var usertime = $(this).val();
    duration = usertime.split(":");
    console.log(duration[0] + duration[1] + duration[2]);
    console.table(duration);
    hours = hours+parseInt(duration[0]);
    minutes = minutes+parseInt(duration[1]);
    seconds = seconds+parseInt(duration[2]);
    // Convert each 60 minutes to an hour
    if (minutes >= 60) {
        hours++;
        minutes -= 60;
    }


    // Convert each 60 seconds to a minute
    if (seconds >= 60) {
        minutes++;
        seconds -= 60;
    }       

    });
     var input = (hours+':'+minutes+':'+seconds);
 $('#total').val(input);
});

Working fiddle for you: http://jsfiddle.net/woe74jq4/

Upvotes: 1

Related Questions