claudios claudios - 5 months ago 17
Javascript Question

Calculate results automatically on keyup function

I've been having hard time on getting the exact value between two input values using

keyup function
. First I get the exact result to calculate and display the result in another input tag but when I add another it displays wrong result. To understand what I mean just check the code below.

HTML:

<input id="ivpd" type="text" name="input_vat_per_document" placeholder="Input VAT per Document">
<input id="gta" type="text" readonly>
<input id="gp" type="text" readonly>


JS:

$('#ivpd').keyup(function(){
var percentage = 12 / 100;
var gta = $('#ivpd').val() / percentage;
var gp = $('#ivpd').val() + $('#gta').val();
if (gta == Number.POSITIVE_INFINITY || gta == Number.NEGATIVE_INFINITY || isNaN(gta))
gta = "N/A"; // OR 0
$('#gta').val(gta);
$('#gp').val(gp);
});


For example:
If I input
964.25
in
ivpd
,
gta
will be
8035.75
but
gp
displays
964.298035.75
which is a wrong result. It shoud be
ivpd
+
gta
.

Answer

value property of input-elements always return DOMString and if any of the operand is of type string, Addition(+) operator will do string concatenation operation not addition.

Cast input-value to Number and then manipulate.

Unary plus (+), The unary plus operator precedes its operand and evaluates to its operand but attempts to converts it into a number, if it isn't already.

Note: Number could be used as well instead of Unary plus (+)

$('#ivpd').keyup(function() {
  var percentage = 12 / 100;
  var gta = +this.value / percentage;
  var gp = +this.value + +$('#gta').val();
  if (gta == Number.POSITIVE_INFINITY || gta == Number.NEGATIVE_INFINITY || isNaN(gta))
    gta = "N/A"; // OR 0
  $('#gta').val(gta);
  $('#gp').val(gp);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input id="ivpd" type="text" name="input_vat_per_document" placeholder="Input VAT per Document">
<input id="gta" type="text" readonly>
<input id="gp" type="text" readonly>

Comments