milano
milano

Reputation: 475

How to display result in input field using javascript

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>

Upvotes: 0

Views: 7008

Answers (2)

Talha
Talha

Reputation: 19282

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

Upvotes: 1

user1823761
user1823761

Reputation:

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

Upvotes: 5

Related Questions