bboooooyintheuk
bboooooyintheuk

Reputation: 143

Trying to sum the values of a dynamic HTML table column

I'm trying to sum the values in the second column (title heading='Value'), however it currently always outputs 0. What am I missing??

(Also the table is populated from a javascript function, which I have included at the bottom of this question).

HTML:

<table id="output_table">
        <tr>
            <th>Name</th>
            <th>Value</th>
        </tr>
        <tfoot>
            <tr>
                <th id="total" colspan="1">Total CPC:</th>
                <td id="sum1"></td>
            </tr>
    </tfoot>
    </table>

JS:

// code to sum CPC column
        var sum1 = 0;
        $("#output_table Value").each(function() {
          sum1 +=  getnum($(this).find("td:eq(1)").text());
          function getnum(t){
            if(isNumeric(t)){
                return parseInt(t,10);
            }
            return 0;
                function isNumeric(n) {
                return !isNaN(parseFloat(n)) && isFinite(n);
                }
          }
        });
        $("#sum1").text(sum1);

JS which populates table:

 $('#sales_order_form_button').click(function(){
    let table_info = [];
    $('.campaignstrategy input[type=checkbox]').each(
        function(index, value){
        if($(this).is(':checked')){
            table_info.push(
                {
                    name: $(this).attr('name'),
                    value: $(this).attr('value'),
                }
            );
        }
    });
    let base64str=btoa(JSON.stringify(table_info));

    window.location = "sales_order_form.html?table_data=" + base64str;
});

// Helper function
        function getUrlParameter(name) {
            name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
            var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
            var results = regex.exec(location.href);
            return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, '    '));
        };

        // actual code
        let table_data = getUrlParameter('table_data');
        let data_from_page_1 = JSON.parse(atob(table_data));

        for(let i=0;i<data_from_page_1.length;i++){
            let row = $("<tr></tr>");
            let recordName = $("<td></td>").text(data_from_page_1[i].name);
            let recordValue = $("<td></td>").text(data_from_page_1[i].value);
            row.append(recordName, recordValue);
            $('#output_table').append(row);
        }

Upvotes: 0

Views: 1818

Answers (2)

Lewis
Lewis

Reputation: 4595

You will want to use tr > td:nth-child(2) selector to select elements in the second column of a table row. Code edited to be as simple as possible - it's simpler to use Number(x) || 0 for the same logic as your two functions.

var sum1 = 0;

$("#output_table tr > td:nth-child(2)").each(
  (_,el) => sum1 += Number($(el).text()) || 0
);

$("#sum1").text(sum1);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="output_table">
  <tr>
    <th>Name</th>
    <th>Value</th>
  </tr>
  <tr>
    <td>Bananas</td>
    <td>10</td>
  </tr>
  <tr>
    <td>Apples</td>
    <td>5</td>
  </tr>
  <tfoot>
    <tr>
      <th id="total" colspan="1">Total CPC:</th>
      <td id="sum1"></td>
    </tr>
  </tfoot>
</table>

Upvotes: 1

blex
blex

Reputation: 25659

If you have a tbody, it will make things easier to select:

var total = $('tbody td:nth-child(2)').toArray().reduce(function (sum, el) {
  var value = isNaN($(el).text()) ? 0 : parseInt($(el).text(), 10);
  return sum + value;
}, 0);

$('#sum1').text(total);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <thead>
    <tr> <th>Name</th><th>Value</th> </tr>
  </thead>
  <tbody>
    <tr> <td>A</td><td>2</td> </tr>
    <tr> <td>B</td><td>5</td> </tr>
    <tr> <td>C</td><td>3</td> </tr>
  </tbody>
  <tfoot>
    <tr> <td>Total CPC:</td><td id="sum1"></td> </tr>
  </tfoot>
</table>

Upvotes: 2

Related Questions