Sum of 2 inputs and appear in real time - Javascript

18

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

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

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

  

The sum of the two numbers is 15.

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

    
asked by anonymous 18.09.2015 / 19:15

6 answers

13

With pure javascript you just get the values of the fields by the id, with document.getElementById() converting the values to int using parseInt() , the number 10 means on which base the number will be converted, add and play 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>
</form>

<div id="resultado"></div>
    
18.09.2015 / 19:21
10

Just assign to the event onblur a function to do the calculation by searching for the values of the sources and assigning the result to the destination. The onblur is antagonic to onfocus , so it will be fired when its input loses focus. You can choose to use the onkeyup event for the calculation to occur at typing time.

HTML

<input type="text" id="num1" onblur="calcular();" />
<input type="text" id="num2" onblur="calcular();" />
<span id="resultado"></span>

JavaScript

function calcular() {
    var num1 = Number(document.getElementById("num1").value);
    var num2 = Number(document.getElementById("num2").value);
    var elemResult = document.getElementById("resultado");

    if (elemResult.textContent === undefined) {
       elemResult.textContent = "O resultado é " + String(num1 + num2) + ".";
    }
    else { // IE
       elemResult.innerText = "O resultado é " + String(num1 + num2) + ".";
    }
}

Edit 1

Code changed to give the result in span instead of input .

    
18.09.2015 / 19:27
8

I'm leaving my answer, only as an alternative to the others.

In the example I am using the onfocus event to trigger the function that calculates the two inputs when the user click in the first field and the onblur event to trigger the function when the user exit from the second field, just to show the difference between the two events.

There are endless other possibilities to do what you want, but that's enough to solve your problem.

function calcular(){
    var valor1 = parseInt(document.getElementById('txt1').value, 10);
    var valor2 = parseInt(document.getElementById('txt2').value, 10);
    document.getElementById('result').value = valor1 + valor2;
}
<input id="txt1" type="text" value="1" onfocus="calcular()"/>
<input id="txt2" type="text" value="1" onblur="calcular()"/>

<input id="result" type="text"/>
    
18.09.2015 / 19:23
6

follows an implementation using the input event and allowing the choice of other operators.

var campo1 = document.getElementById("campo1");
var campo2 = document.getElementById("campo2");
var operador = document.getElementById("operador");
var resultado = document.getElementById("resultado");
var somenteNumeros = new RegExp("[^0-9]", "g");

var toNumber = function (value) {
  var number = value.replace(somenteNumeros, "");    
  number = parseInt(number);    
  if (isNaN(number)) 
    number = 0;
  return number;
}

var somenteNumeros = function (event) {
  event.target.value = toNumber(event.target.value);
}

var onInput = function (event) {
  var num1 = toNumber(campo1.value);
  var num2 = toNumber(campo2.value);
  var calc = num1 + " " + operador.value + " " + num2
  resultado.textContent = calc + " = " + eval(calc);
}

campo1.addEventListener("input", somenteNumeros);
campo2.addEventListener("input", somenteNumeros);

campo1.addEventListener("input", onInput);
campo2.addEventListener("input", onInput);
operador.addEventListener("input", onInput);

onInput();
#operador {
  appearance: none;
  -moz-appearance: none;
  -webkit-appearance: none;
  -o-appearance: none;
}

select::-ms-expand {
  display: none;
}
<input id="campo1" type="number" />
<select id="operador">
  <option value="+" selected>+</option>
  <option value="-">-</option>
  <option value="*">*</option>
  <option value="/">/</option>
  <option value="%">%</option>
</select>
<input id="campo2" type="number" />
<span id="resultado"></span>
    
18.09.2015 / 21:45
3

Here is an example of a sum of 3 inputs, as the user goes typing it is already calculating total, as shown in the example below:

<div id="qtde_elementos">
    <form action="" method="post">
        <div>
            <label>Valor 1:</label>
            <input data-id="0" class="qtde" type="number" placeholder="0" size="1" maxlength="2" max="10" min="0" step="0">
        </div>
        <div>
            <label>Valor 2:</label>
            <input data-id="1" class="qtde" type="number" placeholder="0" size="1" maxlength="2" max="10" min="0" step="0">
        </div>
        <div>
            <label>Valor 3:</label>
            <input data-id="2" class="qtde" type="number" placeholder="0" size="1" maxlength="2" max="10" min="0" step="0">
        </div>
    </form>
</div>
<div class="total" data-total>Total: <span>R$ 0,00</span>
</div>

The javaScript code is this:

$('[data-id]').change(function () {
    var data = {
        id: $(this).data('id'),
        value: $(this).val()
    }
    $('body').trigger('total.update', [data]);
});

(function () {
    var Total = function (el) {
        this.$el = el;
        this.value = 0;
        this.products = new Array();
        $('body').on('total.update', $.proxy(this, 'update'));
    }
Total.prototype.update = function (e, data) {
    this.products[data.id] = data.value
    this.value = this.products.reduce(this.reduce);
    this.render.apply(this);
}

Total.prototype.reduce = function (prev, current) {
    return parseFloat(current) + parseFloat(prev);
}

Total.prototype.render = function () {
    this.$el.find('span').html(currencyFormatted(parseFloat(this.value), 'R$'));
}

$(document).ready(function () {
    $el = $('[data-total]');
    var instance = $el.data('total-instance') || new Total($el);
    $el.data('total-instance', instance);
});
})();

function currencyFormatted(value, str_cifrao) {
    return str_cifrao + ' ' + value.formatMoney(2, ',', '.');
}

Number.prototype.formatMoney = function (c, d, t) {
    var n = this,
        c = isNaN(c = Math.abs(c)) ? 2 : c,
        d = d == undefined ? "." : d,
        t = t == undefined ? "," : t,
        s = n < 0 ? "-" : "",
        i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "",
        j = (j = i.length) > 3 ? j % 3 : 0;
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?  =\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
  };
    
18.09.2015 / 19:24
0

An alternative is to use framework to automate the work for you. The following example is using AngularJS :

angular
  .module('app', [])
  .controller('SomaController', SomaController);

function SomaController() {
  var vm = this;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><divng-app="app" ng-controller="SomaController as vm">
  <input type="number" ng-model="vm.numero1" />

  <input type="number" ng-model="vm.numero2" />
  <br>
  <br>
  <span ng-if="vm.numero1 !== undefined && vm.numero2 !== undefined">A soma dos dois numeros é {{vm.numero1 + vm.numero2}}.</span>
</div>

As you can see, with a small amount of code it is already possible to exchange information between JavaScript and HTML reaching the desired result.

    
28.08.2017 / 06:13