简体   繁体   中英

Display vat value in text box

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/

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"/>

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);

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()

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));
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM