I have the following table structure:
<table width="960" border="1" align="center" id="activity_table">
<tr>
<td width="192">Activity</td>
<td width="192" align="center">Option 1</td>
<td width="192" align="center">Option 2</td>
<td width="192" align="center">Total</td>
</tr>
<tr>
<td>Activity 1</td>
<td align="center">
<input type="text" name="activity_1_option_1" id="activity_1_option_1" value="0" class="col1" size="10" />
</td>
<td align="center">
<input type="text" name="activity_1_option_2" id="activity_1_option_2" value="0" class="col2" size="10" />
</td>
<td align="center">
<input type="text" name="activity_1_total" id="activity_1_total" value="0" class="" size="10" readonly />
</td>
</tr>
<tr>
<td>Activity 2</td>
<td align="center">
<input type="text" name="activity_2_option_1" id="activity_2_option_1" value="0" class="col1" size="10" />
</td>
<td align="center">
<input type="text" name="activity_2_option_2" id="activity_2_option_2" value="0" class="col2" size="10" />
</td>
<td align="center">
<input type="text" name="activity_2_total" id="activity_2_total" value="0" class="" size="10" readonly />
</td>
</tr>
<tr>
<td>Activity 3</td>
<td align="center">
<input type="text" name="activity_3_option_1" id="activity_3_option_1" value="0" class="col1" size="10" />
</td>
<td align="center">
<input type="text" name="activity_3_option_2" id="activity_3_option_2" value="0" class="col2" size="10" />
</td>
<td align="center">
<input type="text" name="activity_3_total" id="activity_3_total" value="0" class="" size="10" readonly />
</td>
</tr>
<tr class="total">
<td>Total</td>
<td align="center">
<input type="text" name="total_activity_1" id="total_activity_1" value="0" class="" size="10" readonly />
</td>
<td align="center">
<input type="text" name="total_activity_2" id="total_activity_2" value="0" class="" size="10" readonly />
</td>
<td align="center">
<input type="text" name="grand_total" id="grand_total" value="0" class="" size="10" readonly />
</td>
</tr>
What I would like to do is to automatically compute the sum on each column and row.
I managed to write a jQuery script to compute the sum on each column, by adding colX (where X is the number of the column) as a class for the columns I want to sum, but I don't know how to do it in order to work for rows.
Here's my script:
$('#activity_table tr:not(.total) input:text').bind('keyup change', function() {
var $table = $(this).closest('table');
var total = 0;
var thisNumber = $(this).attr('class').match(/(\d+)/)[1];
$table.find('tr:not(.total) .col'+thisNumber).each(function() {
total += +$(this).val();
});
thisNumber++;
$table.find('.total td:nth-child('+thisNumber+') input').val(total);
});