Summing text fields when pressing keys causes problems in the first field of the line

I have a table. I am trying to figure out the summation as shown below: td(1) + td(2) + td(3) = td(4) , td(5) + td(6) + td(7) = td(8) , td(9) + td(10) + td(11) = td(12) .

Here is my code:

 $(document).ready(function () { $('#table').on('keyup', 'input', function () { $("#table tr").slice(2).find("td:nth-child(4n + 1)").each(function () { var sum = 0; $(this).prevAll(':lt(3)').find('input').each(function () { sum += (+this.value || 0) }); $(this).find('input').val(sum) }) }) }) 

This code works just fine. But my problem is that I cannot enter anything in the first column (i.e. td:eq(0) ). What is wrong with my code?

http://jsfiddle.net/b0svwpnn/3/

+5
source share
1 answer

You need to explicitly exclude the first input from the nth-child allocation, which you can achieve using :not() . Try the following:

 $("#table tr").slice(2).find("td:nth-child(4n + 1):not(:first)") 

Updated script

+4
source

All Articles