Muhammad Naeem
Muhammad Naeem

Reputation: 39

Add three numbers and display result in textbox with Javascript

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>

Upvotes: 1

Views: 8842

Answers (2)

Tomas Reimers
Tomas Reimers

Reputation: 3292

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/

Upvotes: 3

MattJ
MattJ

Reputation: 11

It's a typo. =>

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

should be Id, not ID

Upvotes: 0

Related Questions