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>

2 Answers 2

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()">
Sign up to request clarification or add additional context in comments.

2 Comments

This is not worse a separate answer, so would you please edit yours so, that conversion to number goes like Number (document.input.time.value) instead of subtracting zero?
@DavidJashi I've just corrected mistakes, not offerring alternatives. Your comment will add useful information to this answer. Thank you :).
1

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

1 Comment

You risk getting concatenation instead of sum.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.