How Do I Collect A Single Column Content
How do I collect a single column content
Solution 1:
You can do it this way, calculateTotal()
will calculate the total of all the previous siblings. And $('.checkallprice').last()
will find the last element and set the text to the result from calculateTotal()
.
$(document).ready(function(){
functioncalculateTotal() {
var total = 0;
jQuery(this).prevAll().each(function() {
total += Number(jQuery(this).text());
});
return total;
}
$('.checkallprice').last().text(calculateTotal);
});
JSFiddle: https://jsfiddle.net/mh5gn7zx/1/
Solution 2:
- Use
.each
to iteratetd
elements - Select last
td
using:last-child
selector - Use
:not(:last-child)
to excludelast-child
- Use
Number
to caststring
tonumber
$('tr').each(function() {
var sum = 0;
$(this).find('td:not(:last-child)').each(function() {
sum += Number(this.textContent);
});
$(this).find(':last-child').text(sum);
})
td:last-child {
background: orange;
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script><table><tr><tdclass="checkallprice">300</td><tdclass="checkallprice">110</td><tdclass="checkallprice">350</td><tdclass="checkallprice">100</td><tdclass="checkallprice">I need Total Here</td></tr><tr><tdclass="checkallprice">10</td><tdclass="checkallprice">120</td><tdclass="checkallprice">30</td><tdclass="checkallprice">40</td><tdclass="checkallprice">I need Total Here</td></tr></table>
Solution 3:
Try this:
Get the html
of every td
except the last one, parse them to Int/Float
and add them up.
$(document).ready(function(){
var sum=0;
$('table tr td').each(function(){
if($(this).is(':last-child'))
{
$(this).html(sum);
}
else
{
sum = sum + parseFloat($(this).html());
}
});
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><table><tr><tdclass="checkallprice">300</td><tdclass="checkallprice">110</td><tdclass="checkallprice">350</td><tdclass="checkallprice">100</td><tdclass="checkallprice">I need Total Here</td></tr></table>
Solution 4:
Try the following:
$(document).ready(function(){
var sum=0;
$('table tr td').not('td:last').each(function(){//select all the td except the last
sum = sum + parseFloat($(this).text());//sum the values
});
$('table tr td:last').text(sum);//append to the last one
});
or if you have multiple tr
$(document).ready(function(){
var sum=0;
$('tr').each(function(){
$(this).find('td').not('td:last').each(function(){//select all the td except the last
sum = sum + parseFloat($(this).text());//sum the values
});
$(this).find('td:last').text(sum);//append to the last one
});
});
Post a Comment for "How Do I Collect A Single Column Content"