I've been having hard time on getting the exact value between two input values using
keyup function
<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>
$('#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);
});
964.25
ivpd
gta
8035.75
gp
964.298035.75
ivpd
gta
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
toNumber
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>