如何计算多行的2个字段的乘积

时间:2013-06-05 10:21:18

标签: javascript html

我正在使用此代码计算2个字段的产品,并且有很多行,当我只使用一行时,结果是在输入字段中打印。但是当我使用多行输入字段时,结果不会打印到文本框中... 我怎么能这样?

代码:

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function updatesum() {
document.input.total.value = (document.input.time.value -0) * (document.input.cost.value -0);
    return false;
}
</script>
</head>
<body>

<form name="input" action="#" method="post" onsubmit="return false;">
Timespent:<input type="text" name="time" value=" ">
Cost:<input type="text" name="cost" value=" ">
Totalcost:<input type="text" name="total" value=" ">
<br>
Timespent:<input type="text" name="time" value=" ">
Cost:<input type="text" name="cost" value=" ">
Totalcost:<input type="text" name="total" value=" ">
<br>
Timespent:<input type="text" name="time" value=" ">
Cost:<input type="text" name="cost" value=" ">
Totalcost:<input type="text" name="total" value=" ">
<br>
Timespent:<input type="text" name="time" value=" ">
Cost:<input type="text" name="cost" value=" ">
Totalcost:<input type="text" name="total" value=" ">
<br>
Timespent:<input type="text" name="time" value=" ">
Cost:<input type="text" name="cost" value=" ">
Totalcost:<input type="text" name="total" value=" ">
<br>
Timespent:<input type="text" name="time" value=" ">
Cost:<input type="text" name="cost" value=" ">
Totalcost:<input type="text" name="total" value=" ">

<input type="submit" value="Submit" onclick="updatesum()">
</form> 

</body>
</html>

1 个答案:

答案 0 :(得分:1)

function updatesum() {
var totalFields = document.input.time.length;
for(var i=0; i <= totalFields; i++){
    document.input.total[i].value = ( document.input.time[i].value * document.input.cost[i].value);
}
return false; }