Add automatically as you type

-1

I have 3 fields (a, b, c) that I need to add and play the value in field (d) as it is being typed, but I can not do it without clicking or typing something after the last number. I tried to use the onkeyup and onkeydown Is there any way?

function id(el) {
  return document.getElementById(el);
}

function calcular(el) {
  var a = id('a').value;
  var b = id('b').value;
  var c = id('c').value;

  id('d').value = parseInt(a) + parseInt(b) + parseInt(c);
}
<input type="text" id="a" name="a" onkeyup="calcular()" onkeydown="calcular()" />
<input type="text" id="b" name="b" onkeyup="calcular()" onkeydown="calcular()" />
<input type="text" id="c" name="c" onkeyup="calcular()" onkeydown="calcular()" />

<input type="text" id="d" name="d" disabled="disabled" />
    
asked by anonymous 02.01.2019 / 14:55

1 answer

2

The problem is that as long as the field has no value, the value attribute will be undefined . If you try to add any value with undefined the result will be NaN .

The solution is you consider the value zero when the attribute is not set by doing something like var a = id('a').value || 0 .

function id(el) {
  return document.getElementById(el);
}

function calcular(el) {
  var a = id('a').value || 0;
  var b = id('b').value || 0;
  var c = id('c').value || 0;

  id('d').value = parseInt(a) + parseInt(b) + parseInt(c);
}
<input type="number" id="a" value="0" name="a" onkeyup="calcular()" onkeydown="calcular()" /> +
<input type="number" id="b" value="0" name="b" onkeyup="calcular()" onkeydown="calcular()" /> +
<input type="number" id="c" value="0" name="c" onkeyup="calcular()" onkeydown="calcular()" /> =

<output id="d">0</output>

Other considerations:

  • I set the value attribute to 0 initially, as this helps in guiding the user;
  • I changed the type of fields to number to take advantage of native basic validations;
  • I changed the result field to <output> to improve document semantics;
  • I added the mathematical operators between fields to improve reading;
02.01.2019 / 15:30