Reputation: 37
I have a dynamically created table and I need to sum the second column of the table. I keep getting 0 as the sum. Am I doing something wrong?
This is the function that's being called upon clicking a sum button, after the table has been created.
function bukkake(){
var sum = 0;
$('.teedee td').eq(1).each(function(){
sum += $(this).val();
});
$('#sum_result').append("The sum is: " + sum)
}
This is the part of the code that creates the table:
$.getJSON("nutritional_value.php?value=" + encodeURI(value), function (data) {
var ttr = $("<tr />");
$.each(data, function(k, v){
var store_1 = v * (parseFloat(uneseno, 10) / 100);
var xstore_1 = store_1.toFixed(2);
$("<td class='teedee'></td>").text(k=='name' ? v : xstore_1).appendTo(ttr);
});
$("#tejbl").append(ttr);
});
Upvotes: 1
Views: 654
Reputation: 55750
Firstly you are using the wrong selector
$('.teedee td').eq(1).each(function(){ // You are trying to select
// a td inside a class
supposed to be
$('td.teedee').eq(1).each(function(){ // But td is the one with the class
Second
A td
does not have the property called .val()
use .text()
instead if you want to target the text inside it
Third
$('td.teedee').eq(1) // Targets only 1 element with index 1
Fourth
Use parseInt
to convert it to a number.
sum += parseInt($(this).text(), 10);
Otherwise you would technically be appending strings instead. So first convert it to a number and then add.
First parse the text
and check if it is not a number
var sum = 0;
$('tr').each(function() {
$('td.teedee', this).eq(1).each(function () {
var value = parseInt($(this).text(), 10);
sum += isNaN(value) ? 0 : value;
});
});
$('#sum_result').append("The sum is: " + sum)
Upvotes: 2