Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get dollar total of all elements with class using jQuery

I have the following html:

<div class="balance">
    <div class="heading">
        <p class="total"><span>00</span></p>
    </div>
    <div class="instance withdrawal">
        <h3>Random</h3>
        <p>desc</p>
        <p class="amount">$350.<span>00</span></p>
    </div>
    <div class="instance deposit">
        <h3>Added in</h3>
        <p>desc</p>
        <p class="amount">$1,250.<span>00</span></p>
    </div>
    <div class="instance withdrawal">
        <h3>Bill</h3>
        <p>desc</p>
        <p class="amount">$50.<span>00</span></p>
    </div>
</div>
<!--end wallet-container left-->

How can i use jQuery to add take total deposits, subtract the withdrawals and append it to the p.total?

like image 853
JordanBarber Avatar asked Sep 26 '22 04:09

JordanBarber


1 Answers

Try this fiddle.

Edited to take floating points into account.

JS

$(function() {
  var total = 0;

  // Check each instance
  $('.instance').each(function() {
    var
      $this = $(this),
      clone = $this.find('.amount').clone(),
      amount = 0,
      floating = 0;

    // Get floating point
    floating = parseFloat('0.' + clone.find('span').text());
    clone.find('span').remove();

    // Get integer amount
    amount = parseInt(clone.text().replace(/\D+/gim, ''), 10);

    if (!isNaN(amount) && amount > 0) {
      if ($this.is('.deposit')) total += (amount + floating); // Deposit
      else if ($this.is('.withdrawal')) total -= (amount + floating); // Withdrawal
    }
  });

  // Format total with commas
  var formatted = ('' + parseInt(total, 10)).split('').reverse().join('');
  formatted = formatted.replace(/(\d{3})/gim, '$1,');
  formatted = formatted.split('').reverse();
  if (formatted[0] == ',') formatted.shift();
  formatted = formatted.join('');

  $('.total').text('$' + parseInt(formatted, 10) + '.');

  var decimal = (total - parseInt(total, 10)) * 100;
  $('.total').append('<span>' + decimal + '</span>')
});
like image 54
KiiroSora09 Avatar answered Sep 29 '22 06:09

KiiroSora09