views:

200

answers:

1

I used the following function I found online and it works perfectly. However, when my user later asked for commas to be included in the numbers, it broke. It only adds the numbers preceding the comma.

Here is the function:

function sumOfColumns(tableID, columnIndex, hasHeader) {
            var tot = 0;
            $("#" + tableID + " tr" + (hasHeader ? ":gt(0)" : ""))
              .children("td:nth-child(" + columnIndex + ")")
              .each(function() {
                  tot += parseInt($(this).html());
              });

Do I need to stop the 'parseInt' piece?

+1  A: 

I'm assuming that you mean that the numbers now have commas as a thousands-separator, like this:

1234567 = "1,234,567"

You can remove all of those commas before you call parseInt, like this:

tot += parseInt($(this).html().replace(',',''));
Ian Clelland
perfect, thank you.
Matt
@Matt be mindful about I18N and L10N though, as usual. This approach will break if you use a different thousands seperator or use a comma as decimal point (as is customary in many localities) to be really on the safe side you'll want to either use a locale-aware approach or put the raw data in a safe place (e.g. a `data-` attribute on the cells).
Alan
You could also try a Regular Expression in your replace and have that strip out any non-digit characters or whitespace to make it a bit more portable.
ajm