0

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);
        }
8
  • 1
    The selector here $("#output_table Value") looks odd. There's no <Value> element in your HTML? Also, when is this script executed? Commented Feb 14, 2020 at 21:07
  • here you can find some useful solutions: stackoverflow.com/a/47484187/11107787 Commented Feb 14, 2020 at 21:08
  • I believe your table in the example is not complete, are values somewhere in <tbody/>? Commented Feb 14, 2020 at 21:09
  • You can't select cells by using the text from the column header, if you want all the cells in that column, you have to refer to the column by number `$('#output_table tbody td:nth-child(2)'), or better yet, if you are controlling the html, tag all the cells you want to add together with the same class to make selecting them easier. Commented Feb 14, 2020 at 21:11
  • @ischenkodv I have added the JS that populates the table to my question! Commented Feb 14, 2020 at 21:13

2 Answers 2

2

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>

Sign up to request clarification or add additional context in comments.

Comments

1

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>

1 Comment

The junk parameter you need to use there, the _ in (_, el), is because jQuery gives you arguments for .each in the form (index, element). In vanilla JS, the same effect can be achieved with document.querySelectorAll("#output_table tr > td:nth-child(2)").forEach(x => sum1 += Number(x) || 0).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.