2015-11-21 53 views
0

您好我有多個持續時間值存儲爲小時分鐘和秒在html輸入如下;JavaScript迭代輸入的持續時間值,並加在一起

<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) 

我想計算總持續時間並將其插入到頁面上的另一個輸入。上面的例子應該輸出總共38個小時。

但是,使用以下代碼我得到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); 
    }); 

}); 

我在下面有一個js小提琴;

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

任何想法,我做錯了,我怎麼能計算出總的持續時間?

回答

1

隊友,你沒有更新的總和,你需要更新它,然後輸出,``檢查:

$("#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); 
}); 

工作搗鼓你:http://jsfiddle.net/woe74jq4/

+0

大,工作,謝謝! – 001221