0

code:

function add() {
  var first = document.getElementById('n3').value;
  var second = document.getElementById('n4').value;
  return first + second;
}
document.getElementById('n5').innerHTML = add();
<input type="text" id="result"/><br/><br/>
<input type="text" id="n3"/><br/><br/>
<button onclick="add();">+</button><br/><br/>
<input type="text" id="n4"/>
<p id="n5"></p>
Mohammad
  • 20,339
  • 15
  • 51
  • 79

4 Answers4

2

Add the assignment to n5 into the add function.

Also, don't forget to cast your input into Number.

function add() {
  var first = document.getElementById('n3').value;
  var second = document.getElementById('n4').value;
  document.getElementById('n5').innerHTML = (Number(first) + Number(second));
}
<input type="text" id="n3"/><br/><br/>
<button onclick="add();">+</button><br/><br/>
<input type="text" id="n4"/>
<p id="n5"></p>
omri_saadon
  • 9,513
  • 6
  • 31
  • 58
1

Update your code to add the value inside the function. Your values are strings and using + will concatenate them. For example 4 + 5 will then become 45.

Convert your value using parseInt to convert it to an int and add the radix, or use Number:

function add() {
    var first = document.getElementById('n3').value;
    var second = document.getElementById('n4').value;
    document.getElementById('n5').innerHTML = parseInt(first, 10) + parseInt(second, 10);;
}
The fourth bird
  • 127,136
  • 16
  • 45
  • 63
0

look these code you could find your mistake:

function add() {
  var first = document.getElementById('n3').value;
  var second = document.getElementById('n4').value;
  var sum=parseInt(first) +  parseInt(second);
  $('#result').val(sum); 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="n3"/><br/><br/>
<input type="text" id="n4"/>
<button onclick="add();">+</button><br/><br/>
<input  id="result"/>
0

Just move the innerHTML setting of n5 inside the add() and convert it number with preceeding +. Also I just remove the unused <input type="text" id="result"/><br/><br/> line of code.

function add() {
  var first = document.getElementById('n3').value;
  var second = document.getElementById('n4').value;
  document.getElementById('n5').innerHTML= +first + +second;
}
<input type="text" id="n3"/><br/><br/>
<button onclick="add();">+</button><br/><br/>
<input type="text" id="n4"/>
<p id="n5"></p>
Always Sunny
  • 32,751
  • 7
  • 52
  • 86