Trevor Daniel
Trevor Daniel

Reputation: 3954

Add Up <TD> Values in Row

I have a number of <td>s in a row and I know the row number.

The <td>s have ids like the following:

TaskHours_0__SaturdayHours TaskHours_0__SundayHours TaskHours_0__MondayHours TaskHours_0__TuesdayHours TaskHours_0__WednesdayHours TaskHours_0__ThursdayHours TaskHours_0__FridayHours

where the 0 increments based on the row number.

I am attempting to write something to add up all the values of each TD when I supply it the row number.

I was hoping to write something like this:

function rowtotal(rownumber){
    var total = 0;
    total = Number($("#TaskHours_0__SaturdayHours").html())
        + Number($("#TaskHours_0__SundayHours").html())
        + Number($("#TaskHours_0__MondayHours").html())
        + Number($("##TaskHours_0__TuesdayHours").html())
        + Number($("#TaskHours_0__WednesdayHours").html())
        + Number($("#TaskHours_0__ThursdayHours").html())
        + Number($("#TaskHours_0__FridayHours").html())
    return total;
}

But I am unable to work out how to substitute the "0" with the parameter "rownumber"

Is there a way to replace the 0 please?

Upvotes: 0

Views: 50

Answers (2)

XCS
XCS

Reputation: 28147

You should use an Array to store the name of the week days in order to reduce duplicate code (DRY coding) and string concatenation to create the jQuery selector.

A cleaner version of your code:

var weekDays = ['Saturday', 'Sunday', 'Monday', 
                'Tuesday', 'Wednesday', 'Thursday', 'Friday'];

function rowtotal(rowNumber){
    var total = 0;

    weekDays.forEach(function(day) {
      total += Number($('#TaskHours_' + rowNumber + '__' + day + 'Hours').html());
    });

    return total;
}

Also, you can also convert a string to a number by prefixing it with the + sign, so instead of this
Number($('#TaskHours_' + rowNumber + '__' + day + 'Hours').html())
You can write this:
+$('#TaskHours_' + rowNumber + '__' + day + 'Hours').html()

Upvotes: 1

Suchit kumar
Suchit kumar

Reputation: 11859

You can use + to concatenate it in between.:

total = Number($("#TaskHours_"+rownumber+"__SaturdayHours").html())

same for other tds.

Upvotes: 3

Related Questions