您好我在html输入中将多个持续时间值存储为小时分和秒,如下所示;
<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);
});
});
我下面有一个小提琴;
http://jsfiddle.net/8geour60/1/
任何想法我做错了什么以及如何计算总持续时间?
答案 0 :(得分: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/