Reputation: 573
How can i sum values from td input in one TR?
<table>
<tr class="here">
<td><input type="text" class="one" value="2" /></td>
<td><input type="text" class="two" value="4" /></td>
<td><input type="text" class="three" value="5" /></td>
<td><input type="text" class="four" value="3" /></td>
<td><input type="text" class="sum" /></td>
<td><input type="text" class="five" value="2" /></td>
</tr>
<tr class="here">
<td><input type="text" class="one" value="2" /></td>
<td><input type="text" class="two" value="4" /></td>
<td><input type="text" class="three" value="5" /></td>
<td><input type="text" class="four" value="3" /></td>
<td><input type="text" class="sum" /></td>
<td><input type="text" class="five" value="2" /></td>
</tr>
<tr class="here">
<td><input type="text" class="one" value="2" /></td>
<td><input type="text" class="two" value="6" /></td>
<td><input type="text" class="three" value="4" /></td>
<td><input type="text" class="four" value="2" /></td>
<td><input type="text" class="sum" /></td>
<td><input type="text" class="five" value="2" /></td>
</tr>
<tr class="here">
<td><input type="text" class="one" value="5" /></td>
<td><input type="text" class="two" value="2" /></td>
<td><input type="text" class="three" value="3" /></td>
<td><input type="text" class="four" value="8" /></td>
<td><input type="text" class="sum" /></td>
<td><input type="text" class="five" value="4" /></td>
</tr>
</table>
I can sum all values with function .each but how to make this for each tr, not td?
I would like sum values from input with class TWO and class THREE and class FOUR and add this to input with class SUM in same TR.
For my example should be:
2 4 5 3 **12** 2 // 4+5+3
2 4 5 3 **12** 2 // 4+5+3
2 6 4 2 **12** 2 // 6+4+2
5 2 3 8 **13** 4 // 2+3+8
Upvotes: 3
Views: 1038
Reputation: 2587
Try below code
$('tr.here').each(function () {
var sum = parseFloat($(this).find('.two').val()) + parseFloat($(this).find('.three').val()) + parseFloat($(this).find('.four').val());
$(this).find('.sum').val(sum);
})
Check this Fiddle
Upvotes: 1
Reputation: 55750
Your code should look like this.
You need to iterate over the td
with the particular class in question and sum up the values. Then assign that value to the input that you were referring to.
$('tr.here').each(function(){
var sum = 0;
$('.two, .three, .four', this).each(function() {
sum += parseFloat(this.value);
});
$('.sum', this).val(sum);
})
Upvotes: 10