views:

25

answers:

2

I have on-fly increasing form rows and 3 columns and each cell contains text box. I want to sum first 2 columns' values to 3rd colums for each row. how can i do that with jquery?

let me visualize more:

     c1    c2    s
r1    5     6   11
r2    7     3   10
.     .     .    .
s   sc1   sc2  sc3

sc1,sc2,sc3 are sum of the related columns as you see. thanks for any efforts!

A: 

Quick and rough version - for each TR, convert the contents of its child TDs to numbers and sum them, then when the summing's done, pop a TD on the end with the value of "sum" as its text.

$("tr").each( function() {
    var sum = 0;
    $("td", $(this)).each( function() {
        sum += Number($(this).text());
    } );
    $(this).append($("<td>").text(sum));
} );
kurreltheraven
A: 

You should build your table like this:

<table class="summonizer">
  <thead>
    <tr>
      <th></th>
      <th>c1</th>
      <th>c2</th>
      <th>s</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>r1</th>
      <td><input type="text" value="5"/></td>
      <td><input type="text" value="6"/></td>
      <td></td>
    </tr>
    <tr>
      <th>r2</th>
      <td><input type="text" value="7"/></td>
      <td><input type="text" value="3"/></td>
      <td></td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <th>s</th>
      <td></td>
      <td></td>
      <td></td>
    </tr>
  </tfoot>
</table>

And your javascript should look like this:

function summonize_table($table) {
  var col_sums = [];
  var row_sums = [];
  var all_sum = 0;
  $table.find('tbody tr').each(function(row){
    row_sums[row] = 0;
    $(this).find('td input[type=text]').each(function(column){
      value = parseInt(this.value);
      row_sums[row] += value;
      if (!col_sums[column]) col_sums[column] = 0;
      col_sums[column] += value;
      all_sum += value;
    });
  });
  $.each(row_sums,function(index,value){
    $table.find('tbody tr:eq('+index+') td:last').html(value);
  });
  $.each(col_sums,function(index,value){
    $table.find('tfoot tr td:eq('+index+')').html(value);
  });
  $table.find('tfoot tr td:last').html(all_sum);
}
$(function(){
  $('table.summonizer input[type=text]').live('change',function(){
    summonize_table($(this).closest('table'));
  });
  $('table.summonizer input[type=text]:first').trigger('change');
});

You can see a working example here: http://jsfiddle.net/my9DF/

jigfox
a little bit beyond of my jquery understanding but working. thanks
edib
what in particular don't you understand? Perhaps I can help you understanding.
jigfox
I am new in jquery but I am in a project to produce a project with jquery. my question is: let the last colums and rows be the sum, what will be the code? i mean 3*3 columns textfield and last ones are sums
edib
See http://jsfiddle.net/my9DF/1/
jigfox