Ad

Get Balance From Jquery Cart

- 1 answer

I enter the amount as input:

<input style="width:200px" type="number" value="amount" class="form-control pull-right prc" placeholder="Enter amount">

my script is:

   $('.form-group').on('input', '.prc', function(){
    var totalSum = 0;
    var currbalance = 0;
    $('.form-group .prc').each(function(){
        var quantity = $(this).val();
        var price=$(this).attr('price');
        var item_amount= parseFloat(price*quantity);
        if ($.isNumeric(quantity)){
            totalSum += parseFloat(item_amount);
        }
        var amount=$(this).attr('amount');
        if ($.isNumeric(amount)){
            currbalance = amount - totalSum;
        }

    });
    $('#total_price').text('RM '+totalSum.toFixed(2));
    $('#balance').text('RM '+currbalance.toFixed(2));});

and I want to display it using balance id:

 <p>Balance: <b id="balance">RM 0.00</b></p>

But my output is not showing. I think my value=amount is wrong.

Ad

Answer

I've added data-amount and data-price to your input's and then I've changed currbalance = amount - totalSum; to currbalance += (amount - totalSum);, because if not then currbalance would not be equal to the total amount of data-amount

Demo

$('.form-group').on('input', '.prc', function() {
  var totalSum = 0;
  var currbalance = 0;
  $('.form-group .prc').each(function() {
    var quantity = $(this).val();
    var price = $(this).attr('data-price');
    var item_amount = parseFloat(price * quantity);
    if ($.isNumeric(quantity)) {
      totalSum += parseFloat(item_amount);
    }
    var amount = $(this).attr('data-amount');
    if ($.isNumeric(amount)) {
      currbalance += (amount - totalSum);
    }

  });
  $('#total_price').text('RM ' + totalSum.toFixed(2));
  $('#balance').text('RM ' + currbalance.toFixed(2));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
  <input style="width:200px" type="number" data-amount="120" data-price="12" class="form-control pull-right prc" placeholder="Enter amount">
  <input style="width:200px" type="number" data-amount="220" data-price="22" class="form-control pull-right prc" placeholder="Enter amount">
</div>

<p>Total: <b id="total_price">RM 0.00</b></p>
<p>Balance: <b id="balance">RM 0.00</b></p>

Ad
source: stackoverflow.com
Ad