jono
jono

Reputation: 75

How to sum the value from a column dynamic table

I want to sum the value of total price. I make a sumTransaction() function. The table is dynamic. Then the value show up to area_total. But how to sum the td value from total price index column?

enter image description here

html code

<div class="container">

    <div class="form" style="margin-top: 50px;">

        <div class="form">
            <div class="form-group">
                <label for="inputEmail3">Input</label>
                <div class="">
                    <input type="text" class="form-control" id="transaction" placeholder="Input Transaction">
                </div>
            </div>
            <div class="form-group">
                <div>
                    <button type="submit" class="btn btn-default" onclick="addTransaction()">Add</button>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <table id="table_trans" class="table table-bordered">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Price</th>
                    <th>Amount</th>
                    <th>Total Price</th>
                </tr>
            </thead>
            <tbody>

            </tbody>
            <tfoot>
                <tr>
                    <td colspan="3">
                        <input type="button" value="Total Price" class="btn btn-success" id="sumTransaction()" />
                    </td>
                    <td id="area_total"></td>
                </tr>
            </tfoot>
        </table>
    </div>
</div>
<!-- /.container -->

script code

function addRow(tags) {
    tags = tags.split(',');
    var total = tags[1] * tags[2];
    tags.push(total);
    var theTable = document.getElementById('table_trans').getElementsByTagName('tbody')[0];
    var newRow = theTable.insertRow(-1);
    var newCell, theText, i;
    for (i = 0; i < tags.length; i++) {
        newCell = newRow.insertCell(i);

        theText = document.createTextNode(tags[i]);
        newCell.appendChild(theText);
    }
}

function addTransaction() {
    var inputTags = document.getElementById('transaction').value;
    addRow(inputTags);
}

function sumTransaction() {
    var td = document.getElementById('table_trans').getElementsByTagName('td');
    var total = 0;

    for (var i in td) {
        if (td[i])
            total += parseInt(td[i].innerHTML);
    }
    document.getElementById('area_total').innerHTML = total;
}

Upvotes: 0

Views: 6498

Answers (2)

Mi-Creativity
Mi-Creativity

Reputation: 9664

In this CodePen

in the addRow() function I changed into this in order to add a class total-price to the last td to grab them easily later - and you can style the total prices separately if you want - in the sumTransaction() function:

for (i = 0; i < tags.length; i++) {
    newCell = newRow.insertCell(i);
    if (i == 3) {
        var lastCell = theTable.lastElementChild.lastElementChild;
        lastCell.className = "total-price";
    }

    theText = document.createTextNode(tags[i]);
    newCell.appendChild(theText);
}

and the sumTransaction() function:

function sumTransaction() {
    var totalPrice = document.getElementsByClassName("total-price");
    var i, priceText, grandTotal = 0;
    for (i = 0; i < totalPrice.length; i++) {
        priceText = parseFloat(totalPrice[i].innerHTML);
        grandTotal += priceText;
    }
    alert(grandTotal);
}

function addRow(tags) {
  tags = tags.split(',');
  var total = tags[1] * tags[2];
  tags.push(total);
  var theTable = document.getElementById('table_trans').getElementsByTagName('tbody')[0];
  var newRow = theTable.insertRow(-1);
  var newCell, theText, i;
  for (i = 0; i < tags.length; i++) {
    newCell = newRow.insertCell(i);
    if (i == 3) {
      var lastCell = theTable.lastElementChild.lastElementChild;
      lastCell.className = "total-price";
    }

    theText = document.createTextNode(tags[i]);
    newCell.appendChild(theText);
  }
}

function addTransaction() {
  var inputTags = document.getElementById('transaction').value;
  addRow(inputTags);
}

function sumTransaction() {
  var totalPrice = document.getElementsByClassName("total-price");
  var i, priceText, grandTotal = 0;
  for (i = 0; i < totalPrice.length; i++) {
    priceText = parseFloat(totalPrice[i].innerHTML);
    grandTotal += priceText;
  }
  alert(grandTotal);
}
<div class="container">
  <div class="form" style="margin-top: 50px;">
    <div class="form">
      <div class="form-group">
        <label for="inputEmail3">Input</label>
        <div class="">
          <input type="text" class="form-control" id="transaction" placeholder="Input Transaction">
        </div>
      </div>
      <div class="form-group">
        <div>
          <button type="submit" class="btn btn-default" onclick="addTransaction()">Add</button>
        </div>
      </div>
    </div>
  </div>
  <div class="row">
    <table id="table_trans" class="table table-bordered">
      <thead>
        <tr>
          <th>Name</th>
          <th>Price</th>
          <th>Amount</th>
          <th>Total Price</th>
        </tr>
      </thead>
      <tbody></tbody>
      <tfoot>
        <tr>
          <td colspan="3">
            <input type="button" value="Total Price" class="btn btn-success" onclick="sumTransaction()" />
          </td>
          <td id="area_total"></td>
        </tr>
      </tfoot>
    </table>
  </div>
</div>

Upvotes: 1

Yeldar Kurmangaliyev
Yeldar Kurmangaliyev

Reputation: 34244

Now, you try to sum up all the integers (and not only integers, which results in NaN) in your table.

You can select all last columns of your table body using the following selector:

function sumTransaction()
{
    var td = document.querySelectorAll('#table_trans > tbody > tr > td:last-child');
    var total = 0;

    for (var i = 0; i < td.length; i++)
    {
        total += parseInt(td[i].innerText);
    }

    document.getElementById('area_total').innerText = total;
}

By the way, this loop can be simplified using Array.prototype.reduce:

var total = [].reduce.call(td, function(a, b) {
    return a + parseInt(b.innerText);
}, 0);

Here is the working JSFiddle demo. The demo runs calculations immediately, without button click.

Upvotes: 1

Related Questions