Reputation: 131
How to auto SUM TD
value (with class="abc"
) when TR
gets clicked, and result of SUM must be inside a TD
with class="total"
.
Below is my HTML:
<table>
<tr>
<td>Bla bla</td>
<td>Bla bla</td>
<td class="abc">30</td>
<tr>
<tr>
<td>Bla bla</td>
<td>Bla bla</td>
<td class="abc">40</td>
<tr>
<tr>
<td>Bla bla</td>
<td>Bla bla</td>
<td class="abc">30</td>
<tr>
<tr>
<td>Bla bla</td>
<td>Bla bla</td>
<td class="total">100</td>
<tr>
</table>
I mean like this:
Upvotes: 3
Views: 2312
Reputation: 28513
It is very simple, just add click event to TR and get all TD values with class="abc"
and sum them to TD with class="total"
. Please see below code
$("tr").click(function(){
var total = 0;
$("td.abc").each(function(){
total+=parseInt($(this).html()); // You can use parseFloat if value is float.
});
$("td.total").html(total);
});
Below is the answer after adding image to the quetion.
Here we can add a simple CSS class="clicked"
to td if its parent tr gets clicked (you can add CSS effects like change bg-color to yellow or some color to show if tr is clicked or not) and remove class when it clicked again...
And on the basis of class="clicked", we will add or remove values from total.
please see below code:
$("tr").click(function(){
var total = $("td.total").html();
if(total==null || total=="")
total = 0;
$(this).find(".abc").each(function(){
var tdCSS = $(this).attr("class");
if(tdCSS.indexOf("clicked")!=-1)
{
total-=parseInt($(this).html()); // You can use parseFloat if value is float.
}
else
{
total+=parseInt($(this).html()); // You can use parseFloat if value is float.
}
$(this).toggleClass("clicked");
});
$("td.total").html(total);
});
Upvotes: 0
Reputation: 57095
var total = $('td.total'), //cache your selectors
td_abc = $('td.abc');
$('tr').click(function () { //handle click event on tr
total.text(function () { //set total text
var sum = 0; //set sum to 0
td_abc.each(function () { //loop through each td element with class abc
sum += +$(this).text() //add it text to sum
});
return sum; //set sum to total
})
});
var total = $('td.total'),
td_abc = $('td.abc');
$('tr').click(function () {
$(this).find('td.abc').data('countme', 1).css('color', 'red');//set .data('countme', 1) to the td.abc inside tr
total.text(function () {
var sum = 0
td_abc.filter(function () {
return $(this).data('countme') == 1; //filter elements which has .data('countme', 1) to be added in sum
}).each(function () {
sum += +$(this).text()
});
return sum;
})
});
Upvotes: 4
Reputation: 28845
I would add a button like: <button id="sum">Sum</button>
and the use this to sum the values:
$('#sum').on('click', function () {
var sum = 0;
$('table td.abc').each(function () {
sum += parseInt(this.innerHTML, 10);
});
$('table td.total').html(sum);
});
Upvotes: 2
Reputation: 67207
Try,
$('tr').click(function(){
var sum = 0;
$('td.abc').each(function(){
sum += parseInt($(this).text(),10);
})
$('td.total').text(sum);
});
Upvotes: 2