如何使用javascript在输入字段中显示结果

时间:2013-06-05 09:48:54

标签: javascript html5

您好我已经编写了这段代码,它接受输入并使用javascript计算2个值。但是我无法在第三个输入字段中打印结果。如何做到这一点?

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

<form name="input" action="#" method="get">
Timespent
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>

2 个答案:

答案 0 :(得分:5)

Working jsFiddle Demo

禁止提交表单:

<form name="input" action="#" method="get" onsubmit="return false;">

您的form名称为input,因此您必须使用该名称进行访问:

function updatesum() {
    document.input.total.value = (document.input.time.value -0) + (document.input.cost.value -0);
}

您的submit按钮也需要引号:

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

答案 1 :(得分:1)

<强> WORKING DEMO

设置输入的id属性,如

<form name="input" action="#" method="get">
Timespent
Timespent:<input type="text" name="time" value=" " id="txtTime">
Cost:<input type="text" name="cost" value=" " id="txtCost">
Totalcost:<input type="text" name="total" value=" " id="txtTotal">
<input type="submit" value="Submit" onclick="updatesum()">
</form>

并在您的函数中

function updatesum() {
   // alert('a');
var time = document.getElementById("txtTime").value;
var cost = document.getElementById("txtCost").value;
var total=0; 
total = (time-0) +( cost-0);
   // alert(total);
document.getElementById("txtTotal").value = total;
return false;
}

你的函数应返回false以防止事件