Sum in 2 inputs and appear in real time - Javascript

Asked

Viewed 65,532 times

21

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

When the person had just filled in, the result of adding the 2 inputs automatically appeared in real time, without having to change page.

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

The sum of the two numbers is 15.

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

  • And what is the doubt/problem?

6 answers

16

With pure javascript just take the values of the fields by id, with document.getElementById() convert the values to int using parseInt(), the number 10 means on which basis 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>

  • Good afternoon, in case I did not want an input with value to calculate the price, but I already managed with the help of friends below.

  • 1

    @Gonçalo the code that makes the calculation is executed only when leaving the n2 no need to click the button.

  • Already etendi, in the case as it would do for that appears the result without being in input, or so that hides the edge of the input?

  • 1

    You can remove the result input, and create a div with the result id and do the assignment, in which case you do not have value, to remove borders you need to use css.

  • I tried to do this only that the result does not appear.

10

Just assign to the event onblur a function for calculating the values of the sources and assigning the result to the destination. The onblur is antagonistic to onfocus, then it will be triggered when your input loses focus. You can choose to use the event onkeyup for the calculation to take place 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 a span instead of a input.

  • Good afternoon, in case I did not want to appear in the answer the input box, as I would do to take out the box and leave only the result?

  • @Gonçalo use a span and assign the result to the property textContet. document.getElementById("resultado").textContent = "A soma dos dois numeros é " + String(num1 + num2) + ".";

  • Friend can give example in code above how to do? Thank you.

9

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

In the example I am using the event onfocus to trigger the function that calculates the two inputs when the user click on in the first field and the event onblur to trigger the function when the user get out of 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"/>

  • Good afternoon, in case I did not want to appear in the answer the input box, as I would do to take out the box and leave only the result?

6

follows an implementation using the event input 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>

3


An alternative is to use a framework that automates the work for you. The following example is using the 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>

<div ng-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.

3

Here is an example of the sum of 3 inputs, as the user is typing he 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 Java 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) : "");
  };
  • 1

    AP didn’t insert the jQuery tag, so maybe it wants to use pure javascript..

Browser other questions tagged

You are not signed in. Login or sign up in order to post.