Created
July 21, 2019 01:53
-
-
Save ramsunvtech/0dd59d21dd4d3a8ff488bb6b86b70281 to your computer and use it in GitHub Desktop.
Table Sum in Vanila
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="utf-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1"> | |
<title>Bittitan</title> | |
</head> | |
<body> | |
<noscript> | |
You need to enable JavaScript to run this app. | |
</noscript> | |
<table id="repair-invoice"> | |
<tr> | |
<th>Item</th> | |
<th>Parts</th> | |
<th>Labor</th> | |
<th>Total</th> | |
</tr> | |
<tr> | |
<td>Automatic Transmission Replacement</td> | |
<td>$1,809.99</td> | |
<td>$830.00</td> | |
<td>?</td> | |
</tr> | |
<tr> | |
<td>Exhaust system replace</td> | |
<td>$279.99</td> | |
<td>$225.00</td> | |
<td>?</td> | |
</tr> | |
<tr> | |
<td>Replace air filter</td> | |
<td>$9.99</td> | |
<td>$0.00</td> | |
<td>?</td> | |
</tr> | |
<tr> | |
<td colspan="3">Total</td> | |
<td>?</td> | |
</tr> | |
</table> | |
<script type="text/javascript"> | |
document.addEventListener("DOMContentLoaded", function () { | |
const forEachNode = (array, callback) => { | |
for (let i = 0; i < array.length; i++) { | |
callback(i, array[i]); | |
} | |
}; | |
const numberise = currencyString => { | |
if (currencyString && typeof currencyString === 'string') { | |
return parseFloat(currencyString.replace(/[$,]/g, '').trim()); | |
} | |
return ''; | |
}; | |
const formatter = new Intl.NumberFormat('en-US', { | |
style: 'currency', | |
currency: 'USD', | |
minimumFractionDigits: 2 | |
}); | |
const rowsNodesList = document.querySelectorAll('#repair-invoice tr'); | |
let grandTotal = 0; | |
forEachNode(rowsNodesList, function (index, node) { | |
const [ item, parts, labour, total ] = node.children; | |
const isTD = ((parts && parts.tagName || '').toLowerCase() === 'td'); | |
if (isTD && !item.getAttribute('colspan') ) { | |
const totalAmount = (numberise(parts.textContent)) + (numberise(labour.textContent)); | |
total.innerHTML = formatter.format((totalAmount)); | |
grandTotal = (grandTotal + totalAmount); | |
} else if (index === rowsNodesList.length - 1) { | |
const [totalEl, grandTotalEl] = node.children; | |
grandTotalEl.innerHTML = formatter.format(grandTotal.toFixed(2)); | |
} | |
}); | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment