Sum in 2 inputs and appear in real time – JavaScript


My question is: I have two type text inputs. One person put a number in input 1 and another number in input 2.

When the person finished filling in, the result of the sum of the 2 inputs would automatically appear in real time, without having to change the page.

If I put it in the first input 5 and in the second input 10, then when I finished filling it out, it looked like this:

The sum of the two numbers is 15.

That is, in real time without having to click on anything or so.


With pure javascript you just get the field values ​​by id, with document.getElementById() convert the values ​​to int using parseInt() , the number 10 means which base the number will be converted to, add and put the result in the input.

function calcular() {
  var n1 = parseInt(document.getElementById('n1').value, 10);
  var n2 = parseInt(document.getElementById('n2').value, 10);
  document.getElementById('resultado').innerHTML = n1 + n2;
<form action="" method="post">
  N1: <input type="text" id="n1" value="10" /> <br> N2: <input type="text" id="n2" value="5" onblur="calcular()" /> <br>

<div id="resultado"></div>
Scroll to Top