Automatically add as typed

Asked

Viewed 26 times

-1

I have 3 fields (a,b,c) that I need to add and play the value in the field (d) as it is being typed, but I can’t do without clicking or typing anything else after the last number. I tried to use the functions 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" />

  • 1

    One option would be to start all fields with 0 as value; another would be to validate if the attribute value is set and when not set 0.

  • gives a look at this function https://api.jquery.com/blur/

  • Anderson, starting as 0 worked perfectly, however I was asked to put a checkbox now in the code, that when it is ticado, sum only the first two values (a,b), otherwise sum all (a,b,c). I’m thinking of a way to check the checkbox too now.

1 answer

2

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

The solution is for you to consider 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 defined the attribute value as 0 initially, as this helps in user guidance;
  • I changed the field guy to number to enjoy native basic validations;
  • I changed the result field to <output> to improve the semantics of the document;
  • I added the mathematical operators between the fields to improve reading;

Browser other questions tagged

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