Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Summation of text fields on keyup causes issues in first field of a row

I have a table.I am trying to find out the summation as 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)
        })
    })
})

The code above works fine. But my problem is, I can't enter any thing to first column (ie, td:eq(0)). Whats wrong with my code?

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

like image 981
Rose Avatar asked Sep 28 '22 13:09

Rose


1 Answers

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

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

Updated fiddle

like image 129
Rory McCrossan Avatar answered Oct 05 '22 08:10

Rory McCrossan