Reputation: 47
How to count a table TD as total using html or php or javascript or css?
Example
<table>
<tr><td> 1000 </td></tr>
<tr><td> 2000 </td></tr>
<tr><td> 3000 </td></tr>
<tr><td> TOTAL 6000 </td></tr>
</table>
Upvotes: 0
Views: 201
Reputation: 622
I think the answer from @Marc B is the better answer to the title of your question.
If you want updates to your MySQL database pushed to your web page in real time, that's a different question - check out Rachet Web Sockets for PHP.
If you want a javascript solution that just calculates your total...
The HTML: Add the same class name to each of the non-total table cells.
<tr><td class="amt"> 3000 </td></tr>
Add a span with an id in the "total" cell.
<tr><td>TOTAL <span id="total">...</span></td></tr>
The Javascript:
Get an HTMLCollection of all the "amt" cells.
const amounts = document.querySelectorAll('.amt');
Get a reference to the "total" cell
const total_cell = document.querySelector('#total');
Declare a variable to hold your calculation.
Let total = 0;
Loop through the amounts, get the contents of each cell as a Number, and add the number to the value of "total".
for (const amt of amounts) {
const number = Number(amt.innerText);
total += number;
}
Then update the "total" cell
total_cell.innerText = total;
And the whole shebang...
const amounts = document.querySelectorAll('.amt');
const total_cell = document.querySelector('#total');
let total = 0;
for (const amt of amounts) {
const number = Number(amt.innerText);
total += number;
}
total_cell.innerText = total;
<table>
<tr><td class="amt"> 1000 </td></tr>
<tr><td class="amt"> 2000 </td></tr>
<tr><td class="amt"> 3000 </td></tr>
<tr><td>TOTAL <span id="total">...</span></td></tr>
</table>
Upvotes: 0
Reputation: 96189
Just for the fun of it: You could keep the output as is (at least the order, i.e. first output the items and then the total/sum) and then change the placement/order of the elements in the rendering of the browser by setting the box-ordinal-group in reverse order.
<!DOCTYPE html>
<html>
<head>
<title>...</title>
<style>
#container {
display: -webkit-box;
display: -moz-box;
display: box;
-webkit-box-orient: vertical;
-moz-box-orient: vertical;
box-orient: vertical;
}
#total {
-webkit-box-ordinal-group: 1;
-moz-box-ordinal-group: 1;
box-ordinal-group: 1;
}
#items {
-webkit-box-ordinal-group: 2;
-moz-box-ordinal-group: 2;
box-ordinal-group: 2;
}
</style>
</head>
<body>
<div id="container">
<div id="items"><!-- though it's before #total in the document -->
<ul><li>a</li><li>b</li><li>c</li><li>d</li><li>e</li></ul>
</div>
<div id="total"><!-- #total will be rendered above #items ...if flexible boxing is supported -->
1234
</div>
</div>
</body>
</html>
Upvotes: 0
Reputation: 360862
so build the table into memory first, THEN output the total. e.g.
while(... fetch from db ... ) {
$html = '... table row ..';
$total += $row['cost'];
}
echo 'Total: ' . $total;
echo $html; // output table contents
Upvotes: 1