Reputation: 6656
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
.
Upvotes: 0
Views: 1402
Reputation: 6975
Try this:
var gp = parseFloat($('#ivpd').val()) + parseFloat($('#gta').val());
Upvotes: 1
Reputation: 36609
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>
Upvotes: 2
Reputation: 10975
Simplest way is to multiply ivpd and gta values with 1
var gta = $('#ivpd').val() / percentage;
var ivpd= $('#ivpd').val();
var gta =gta*1;
var gp =(ivpd *1)+ (gta*1);
codepen url for reference- http://codepen.io/nagasai/pen/EyPVVE
Upvotes: 1