1

i was just trying to write a code that will use 3 input fields and show their sum into result field. If a person put data in field 1, the result field should show the data in result field and when user put data in second field, result field should show the sum of field 1 and field 2 and when user put data into field 3, their sum should be show on result field. I write below code but not got any success. I am a new learner.

<body>
Field 1: <input type="text" id="num1" onkeyup="sum();" > </br>
Field 2: <input type="text" id="num2" onkeyup="sum();" > </br>
Field 3: <input type="text" id="num3" onkeyup="sum();"> </br>
Sum: <input type="text" id="final"  />



<script type="text/javascript">

function sum()
{


var w = document.getElementById('num1').value;

var x = document.getElementById('num2').value;

var y = document.getElementById('num3').value;

var z=parseInt(w)+parseInt(x)+parseInt(y);


document.getElementByID('final').value=z;

}       
</script>

</body>
3
  • You can use jQuery (if you don't know how to use it, please comment here). Commented Jan 28, 2017 at 21:54
  • Try fixing this document.getElementByID('final').value=z typo, to getElementById Commented Jan 28, 2017 at 21:58
  • thanks dear. I just correct it. Commented Jan 28, 2017 at 22:03

2 Answers 2

3

Two issues:

(1) Small typo in your last line, you used getElementByID instead of getElementById

(2) You need to account for the case where there is no value, one way to do this is to or it with 0 (which evaluates to 0 if there is no value).

Here is a working example:

function sum()
{
  var w = document.getElementById('num1').value || 0;
  var x = document.getElementById('num2').value || 0;
  var y = document.getElementById('num3').value || 0;

  var z=parseInt(w)+parseInt(x)+parseInt(y);

  document.getElementById('final').value=z;
};   

https://jsfiddle.net/yq60qad0/

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks mate. I spend a day on this. Glad to get working code.
Just glad to be helpful :)
0

It's a typo. =>

document.getElementByID('final').value=z;

should be Id, not ID

2 Comments

thanks for the correcting me. But still when i put input in first two fields result field shows NaN...how to handle it?
It's because all the numbers are not defined yet to sum them up. NaN means "not a number", Your code is trying to add up "5", "8", and undefined, for example. Your code works properly only when all three inputs are done.

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.