1

I trying to get result of grand total with 2 decimals. If i add 3.56 with 4.28 subtotal show result with decimals but grand total show .00 on decimals.

html code

<form>
<div>Quantity:
    <input type="text" class="qty">Unit price:
    <input type="text" class="unit">Amount:
    <input type='text' class='amount'>
</div>

<div>Quantity:
    <input type="text" class="qty">Unit price:
    <input type="text" class="unit">Amount:
    <input type='text' class='amount'>
</div>Total All:
<input type="text" class="result">

jquery code

$(function () {
    $('.unit,.qty').on('change', function () {
        var unit = $(this).hasClass('unit') ? $(this).val() : $(this).siblings('.unit').val();
        var qty = $(this).hasClass('qty') ? $(this).val() : $(this).siblings('.qty').val();
        unit = unit || 0;
        qty = qty || 0;
        var val = unit >= 1 && qty >= 1 ? parseFloat(unit * qty) : 0;
        $(this).siblings('.amount').val(val.toFixed(2));
        var total = 0;
        var update = false;
        $('.amount').each(function () {
            val = parseFloat($(this).val()) | 0;
            total = val ? (parseFloat(total + val)) : total;
        });
        $('.result').val(total.toFixed(2));
    });
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Paul
  • 11
  • 1
  • Step through your code, evaluate all the significant variables as you go. Eventually, you'll hit an unexpected value and/or path of execution, that'll help you isolate the cause. –  Jan 26 '15 at 10:04
  • Check if this helps: _http://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-money-in-javascript_ –  Jan 26 '15 at 10:07
  • Have you input all field ? LOL, i tried your code and it's working properly in firefox and internet explorer – Iswanto San Jan 26 '15 at 10:16

1 Answers1

1

Your use of ternaries and traversal logic was a little off. Try this:

$('.unit, .qty').on('change', function () {
    var $container = $(this).closest('div');
    var unit = $container.find('.unit').val() || 0;
    var qty = $container.find('.qty').val() || 0;
    var val = parseFloat(unit * qty);
    var total = 0

    $container.find('.amount').val(val.toFixed(2));
    $('.amount').each(function () {
        total += parseFloat($(this).val() || 0);
    });    
    $('.result').val(total.toFixed(2));
});

Example fiddle

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339