Skip to content Skip to sidebar Skip to footer

Get The Sum Of 2nd Column In Html Table

input :
100
200
from the input it should return me the sum=30

Solution 1:

eq starts with 0 index.The output 100200 is because it is concatenating the string instead of adding the values.Also use parseInt to convert the number from string to integer.

functionSave_Name() {
  varAmount = 0;
  // will get all trvar n = $("#table1 tr");
  n.each(function(i, v) {
    // table have only one td per tr so eq(0) will give first td// trim is used to remove any white spaceAmount += parseInt($(v).eq(0).text().trim(), 10)

  })
  console.log(Amount)
}
Save_Name()
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><tableid="table1"><tr><td>100</td></tr><tr><td>200</td></tr></table>

Solution 2:

Here's another way to do the same thing. Basically, I use map to create a map of integer values, then I use "get" to convert them into an array, and finally I use reduce to calculate the sum of the values in the array.

P.S.: To calculate the second column, all you need to do is to use nth-child(2) instead of nth-child(1).

$(function(){
  var sum = $('#table1 tr td:nth-child(1)').map(function() {
    returnparseInt($(this).html(), 10)
  }).get().reduce(function(a, v){
    return a + v;
  }, 0);

  console.log(sum);
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script><tableid="table1"><tr><td>100</td></tr><tr><td>200</td></tr></table>

Solution 3:

I have alert the value of sum Amount and it is equal to 300 .

You were doing some mistake as eq(2) instead of eq(0)

But Here's the working snippet:

functionSave_Name()
    {
       
        varAmount = 0;
        var n = $('#test tr').length;
       // alert(n);if (n - 1 > 0)
        {
            for (var i = 0 ; i < n; i++)
            {
                varAmt = $("#test").find("tr").eq(i).find("td").eq(0).text();
                Amount += parseFloat(Amt);

            }
          alert(Amount);
        }
}

Save_Name();
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><tableid='test'><tr><td>100 </td></tr><tr><td>200 </td></tr></table>

Post a Comment for "Get The Sum Of 2nd Column In Html Table"