0

There is a table

SUM | <input type="text"> | <input type="text"> |
    | <input type="text"> | <input type="text"> |
    | <input type="text"> | <input type="text"> |
SUM | <input type="text"> | <input type="text"> |
    | <input type="text"> | <input type="text"> |
FOO | <input type="text"> | <input type="text"> |
BAR | <input type="text"> | <input type="text"> |

I want to get sum of columns below "SUM row" when input value is changed. If there is other column ex FOO BAR it shouldn't be count to sum.

What is aproach here? Dummy idea: every column has reference where it value will be summed.

Fiddle for quick start: http://jsfiddle.net/igos/vNxzu/

EDIT It should sum up till next sum row right.

row 0 col 0  = row 1 col 0  + row 2 col 0
row 0 col 1  = row 1 col 1  + row 2 col 1
row 3 col 0  = row 4 col 0
row 3 col 1  = row 4 col 1

It should be dynamic, so when more rows come it will automatically add more rows.

7
  • it should sum up till next sum row right? Commented May 14, 2013 at 11:24
  • why not just add a class (e.g. class="sumCell") and just use jQuery to select those cells and sum the value when a value changes? Commented May 14, 2013 at 11:25
  • @DavidHoerster because I don't know how to determine if I want to sum to first sumRow or the second. Commented May 14, 2013 at 11:27
  • so in your fiddle there 'll be 2 sums each one equal to (8 cells * 3 rows) right?? Commented May 14, 2013 at 11:29
  • 1
    Try jsfiddle.net/arunpjohny/ne5DM/3 Commented May 14, 2013 at 11:40

1 Answer 1

2

Try

$('tr.sumToUp input').change(function(){
    var $this = $(this), $row = $this.closest('tr'), $sum = $row.prevAll('.sumToMe').first(), $rows = $sum.nextUntil('.sumToMe', '.sumToUp'), index = $this.closest('td').index();

    var sum = 0;
    $rows.each(function(){
        var val = $(this).find('td').eq(index).find('input').val();
        sum += (+val);
    })
    $sum.find('td').eq(index).find('input').val(sum);
});

Demo: Fiddle

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.