Sprunkas Sprunkas - 6 months ago 11
Javascript Question

Two digits after comma

I have disabled input field, where result goes ("Kiekis" * "Kaina" = "Suma"), but result in a lot of situations displayed with more than 2 digits (Like 3 * 2.93) even if I used JS toFixed(2) function.

$('#quantity, #price').on('keyup change', function() {
$('#total').val($('#quantity').val() * $('#price').val()).toFixed(2);
});


Here is all my code in JSFiddle:
https://jsfiddle.net/w5qz5exe/

Thanks for help in advance! :)

A.J A.J
Answer

You are attaching events on the input fields before they are loaded on the DOM. So, attach event in parent:

Also toFixed should be inside val, as whatever value is passed in parameter of val function is set as value of that element. So you need to send formatted value in this funciton :

Example:

$('div.row').on('keyup change', '#quantity, #price ', function() {
     $('#total').val(($('#quantity').val() * $('#price').val()).toFixed(2));
 });

Updated Fiddle - link