UmarAbbasKhan UmarAbbasKhan - 1 month ago 4
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

elements with name='gross_val'. I have following

<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
elements have been dynamically populated with values in them. Some of these
elements have gross total values of the
they are inside and some of them have not been populated yet. I just want to sum those
elements who have been populated with gross total values. And then show that value in another

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) {
// this line adds the values inside of gValues array
sum = Number(gValues.reduce(add, 0));
$(document).on("keyup", function() {
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
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
elements who have some value inside of them.


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;