<table id="tab" border="1">
<tr>
<td>One</td><td>123</td><td></td><td>32</td>
</tr>
<tr>
<td>Two</td><td>52</td><td></td><td>53</td>
</tr>
<tr>
<td>Three</td><td>234</td><td></td><td>56</td>
</tr>
</table>
$('#tab').click(function(){
sum();
})
function sum(){
//????
}
How is the best method for sum column from second and fourth TD and fill in to third TD for each TR?
LIVE: /
<table id="tab" border="1">
<tr>
<td>One</td><td>123</td><td></td><td>32</td>
</tr>
<tr>
<td>Two</td><td>52</td><td></td><td>53</td>
</tr>
<tr>
<td>Three</td><td>234</td><td></td><td>56</td>
</tr>
</table>
$('#tab').click(function(){
sum();
})
function sum(){
//????
}
How is the best method for sum column from second and fourth TD and fill in to third TD for each TR?
LIVE: http://jsfiddle/bYf8C/
Share Improve this question asked Apr 18, 2013 at 14:27 marksoodrigmarksoodrig 391 silver badge3 bronze badges4 Answers
Reset to default 4function sum(){
$("tr").each(function(){
var sum = parseFloat($(this).find("td:eq(1)").text()) +
parseFloat($(this).find("td:eq(3)").text());
$(this).find("td:eq(2)").text(sum);
})
}
Here, have a fiddle: http://jsfiddle/bYf8C/10/
demo: http://jsfiddle/bYf8C/2/
$('#tab').click(function(){
sum();
})
function sum(){
$('#tab').find('tr').each(function(){
var first = $(this).children('td:eq(1)').text(),
second = $(this).children('td:eq(3)').text();
$(this).children('td:eq(2)').html(function(){
return parseInt(first) + parseInt(second);
});
});
}
As Bojangles suggested in the ments, children()
is faster than find()
, and :eq
is faster than :nth-child
. My edit reflects that.
Here it is:
$(function() {
$('#tab').on('click', function sum() {
$('tr', this).each(function(index, tr) {
var td1, td3;
td1 = parseInt(tr.children[1].textContent, 10);
td3 = parseInt(tr.children[3].textContent, 10);
tr.children[2].innerHTML = td1 + td3;
});
});
});
Example: http://jsbin./uvuzeq/1/edit
function sum(){
$('#tab tr').each(function() {
var number1 = parseInt($(this).find("td").eq(1).html());
var number2 = parseInt($(this).find("td").eq(3).html());
$(this).find("td").eq(2).html(number1 + number2)
});
}
Fiddle: http://jsfiddle/bYf8C/11/