Reputation: 280
Does anyone know why I'm getting a value NaN in the vat input box? When I enter a value of qty it always gives me a NaN value.
$('#sales_qty').keyup(function(){
var qty = parseFloat($('#sales_qty').val()) || 0;
var sub_total = parseFloat($('#sales_sub_total').val()) || 0;
var vat = 0.12;
var sales_total = $('#sales_total').val((qty * sub_total).toFixed(2));
$('#sales_vat').val((sales_total * vat).toFixed(2));
});
JSFiddle: https://jsfiddle.net/yv6zks1g/
Upvotes: 2
Views: 286
Reputation: 1120
Because sales_total
is the element itself, (not the value). you should add another val()
at the end to get the value.
$('#sales_qty').keyup(function(){
var qty = parseFloat($('#sales_qty').val()) || 0;
var sub_total = parseFloat($('#sales_sub_total').val()) || 0;
var vat = 0.12;
var sales_total = $('#sales_total').val((qty * sub_total).toFixed(2)).val();
$('#sales_vat').val((sales_total * vat).toFixed(2));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="sales_qty" type="text" placeholder="sales_qty" />
<input id="sales_sub_total" type="text" placeholder="sales_sub_total" />
<input id="sales_total" type="text" placeholder="sales_total" />
<input id="sales_vat" type="text" placeholder="sales_vat"/>
Upvotes: 3
Reputation: 9
Its because you are not getting the real value of sales total input
and you are just assigning a new value for it. On this line
var sales_total = $('#sales_total').val((qty * sub_total).toFixed(2));
To fix it you have to get again the value of sales total input
by using the val() method
. Your code should look like this
$('#sales_qty').keyup(function(){
var qty = parseFloat($('#sales_qty').val()) || 0;
var sub_total = parseFloat($('#sales_sub_total').val()) || 0;
var vat = 0.12;
$('#sales_total').val((qty * sub_total).toFixed(2)); // assign the value
var sales_total = $('#sales_total').val() // grab the value
$('#sales_vat').val((sales_total * vat).toFixed(2));
});
Upvotes: 0
Reputation: 176
As in these two lines you are parsing float value from your input elements,
var qty = parseFloat($('#sales_qty').val()) || 0;
var sub_total = parseFloat($('#sales_sub_total').val()) || 0;
You need to set your inputs like these,
<input id="sales_qty" type="number" />
<input id="sales_sub_total" type="number" />
So that it is not possible to enter anything other than number. This will get you rid of the NaN problem.
Also you need to put
var sales_total = $('#sales_total').val((qty * sub_total).toFixed(2)).val()
Upvotes: 0
Reputation: 31
i think its because of the var sales_total = $('#sales_total').val((qty * sub_total).toFixed(2));
line.
instead of $('#sales_total').val((qty * sub_total).toFixed(2));
add var sales_total = (qty * sub_total).toFixed(2);
Upvotes: 0