UmarAbbasKhan UmarAbbasKhan - 2 months ago 9
HTML Question

How to sum the values of not empty <td> elements in Javascript or JQuery

I am trying to make a sum total of all the html inside of

<td>
elements with name='gross_val'. I have following
<td>
elements:

<tr><td name="gross_val" align="right" title="gross_val1" ></td></tr>
<tr><td name="gross_val" align="right" title="gross_val2" ></td></tr>
<tr><td name="gross_val" align="right" title="gross_val3" ></td></tr>
<tr><td name="gross_val" align="right" title="gross_val4" ></td></tr>
<tr><td name="gross_val" align="right" title="gross_val5" ></td></tr>


All of these
<td>
elements have been dynamically populated with values in them. Some of these
<td>
elements have gross total values of the
<tr>
they are inside and some of them have not been populated yet. I just want to sum those
<td>
elements who have been populated with gross total values. And then show that value in another
<td>
element.

I have written the following JQuery and Javascript for this:

function computeGrossValTotal() {
var x = $("td[name='gross_val']");
var gValues = [];
$(x).each(function(index) {
// this line takes up the raw html inside of that td element
var valc = $(this).html();
// this line strips all the currency and other characters and symbols
// off the 'valc' variable and makes it in an integer format
var val = Number(WC(valc));
if (val) {
gValues.push(val);
}
});
// this line adds the values inside of gValues array
sum = Number(gValues.reduce(add, 0));
alert(sum);
}
$(document).on("keyup", function() {
computeGrossValTotal();
});
function WC(x) { return Number(x.match(/(?:\d+|\.)/g).join("")); }
function add(a, b) {return a + b;}


The problem I am facing is that sum does not alert unless all the
<td>
elements have some html inside of them. I cannot get to remove the empty td elements from the equation. Please can someone guide me as to how to only sum the
<td>
elements who have some value inside of them.

Answer

WC needs to check that x.match() finds something, so it doesn't call join on null.

function WC(x) {
    var nums = x.match(/(?:\d+|\.)/g);
    if (nums) {
        return Number(nums.join(''));
    } else {
        return null;
    }
}
Comments