Nadee
Nadee

Reputation: 342

getting first time total is fine, but when changing the discount or quantity will give incorrect result


html page total text field markup

<label class="control-label col-xs-5">Total: </label>
  <div class="col-xs-6">
    <input type="text" name="totalprice" id="finaltotalprice" class="form-control" disabled> <!-- final total value is here -->
  </div>


JavaScript/jQuery function for dynamically adding rows

there in no error in executing this bit of code

// dynamically changing the row id for table rows
let rowId = 0;

$("#soid").change(function() {
 $.get("../ajax/ajax_product.php?type=get_sales_order_list", {salesOrderId: $("#soid").val()} , function (data) {
  if(data) {
     console.log(data);
     let orderItems = JSON.parse(data);
     console.log(orderItems);
     $("#sales_item_list").html('');

      for(let list in orderItems) {
          $("#sales_item_list").append("<tr>" + 
          "<td><input type='text' name='quantity[]' class='form-control' id='quantity_"+ rowId +"' value='"+ orderItems[list].sales_list_item_quantity +"' onchange='calculateItemTotal("+ rowId +")' ></td>"+ 
          "<td><input type='hidden' name='unitprice[]' id='unitprice_"+ rowId +"' class='form-control' value='"+ orderItems[list].unit_price +"' readonly>"+ orderItems[list].unit_price +"</td>" + 
          "<td><input type='text' name='discount[]' class='form-control'  id='discount_"+ rowId +"' onchange='calculateItemTotal("+ rowId +")'></td>" + 
          "<td><input type='text' name='itemtotalprice[]' class='form-control' id='itemtot_"+ rowId +"' ></td>"  + 
          "</tr>");
   rowId++;
                }
            }

        });
    });


calculateItemTotal() function

    let finalTot = 0;
    function calculateItemTotal(data) {
        let quantity = parseInt($("#quantity_"+data).val()); // take the quantity value to quantity variable -- ok
        if(isNaN(quantity)) quantity = 0; // make it 0 if it is not a number

        let unitPrice = parseFloat($("#unitprice_"+data).val()); // take the unit price value to the unit price variable --ok
        if(isNaN(unitPrice)) unitPrice = 0.00;

        let tot = quantity * unitPrice; // calculation is ok
        let discount = (parseFloat($("#discount_"+data).val())/100 * tot).toFixed(2); // calculation is ok
        if(isNaN(discount)) discount = 0.00;

        let net_total = tot - discount; // this is also ok

        let with2Decimals = parseFloat(net_total).toFixed(2); // this is also ok

        $("#itemtot_"+data).val(with2Decimals); // set the calculated price of product item -- ok

        // this is also ok
        let convertToNumber = parseFloat($("#itemtot_"+data).val());

        putFinalTotal(convertToNumber); // calling for the function to set the final total, -- ok
    }
    
    
function putFinalTotal(convertToNumber) {
   finalTot = finalTot + convertToNumber;
   console.log(typeof(finalTot));
   $("#finaltotalprice").val(finalTot.toFixed(2)); // set the total value to the "total" text field
}


first time calculation

correctly adding the item totals

enter image description here


when ever if I changed quantity or discount, total value gives me incorrect value

ex:- I changed quantity from 10 to 100, gives me correct item total but incorrect total value

correct answer should be 14400 but gives me 15600

enter image description here

can please someone can give me insight, how to figure out this issue.

Upvotes: 0

Views: 82

Answers (1)

Zavarock
Zavarock

Reputation: 339

You need to subtract Item total price before a new sum because its current value is saved in finalTot.

Try:

let finalTot = 0;

function calculateItemTotal( data ) {
    const rowTotalElement = $( '#itemtot_' + data );
    const currentRowTotal = parseFloat( rowTotalElement.val() );
    if ( !isNaN( currentRowTotal ) ) {
        finalTot -= currentRowTotal;
    }

    let quantity = parseInt( $( '#quantity_' + data ).val() ); // take the quantity value to quantity variable -- ok
    if ( isNaN( quantity ) ) {
        quantity = 0;
    } // make it 0 if it is not a number

    let unitPrice = parseFloat( $( '#unitprice_' + data ).val() ); // take the unit price value to the unit price variable --ok
    if ( isNaN( unitPrice ) ) {
        unitPrice = 0.00;
    }

    let tot = quantity * unitPrice; // calculation is ok
    let discount = (parseFloat( $( '#discount_' + data ).val() ) / 100 * tot).toFixed( 2 ); // calculation is ok
    if ( isNaN( discount ) ) {
        discount = 0.00;
    }

    let net_total = tot - discount; // this is also ok

    let with2Decimals = parseFloat( net_total ).toFixed( 2 ); // this is also ok

    rowTotalElement.val( with2Decimals ); // set the calculated price of product item -- ok

    // this is also ok
    let convertToNumber = parseFloat( rowTotalElement.val() );

    putFinalTotal( convertToNumber ); // calling for the function to set the final total, -- ok
}

Upvotes: 1

Related Questions