最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - How to display result in input field using javascript - Stack Overflow

programmeradmin6浏览0评论

Hi i have written this code that takes input and calculates 2 values using javascript. but i am not able to print the result in third input field.how to do this?

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

Hi i have written this code that takes input and calculates 2 values using javascript. but i am not able to print the result in third input field.how to do this?

<!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>
Share Improve this question asked Jun 5, 2013 at 9:48 milanomilano 4755 gold badges13 silver badges20 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

Working jsFiddle Demo

Disable submitting your form:

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

Your form name is input, so you must access it with it:

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

Also your submit button need quotes:

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

WORKING DEMO

Set the id attribute of your inputs like

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

and in your function

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;
}

your function should return false to prevent event

发布评论

评论列表(0)

  1. 暂无评论