screen_rotation
Copied to Clipboard
<!DOCTYPE html> <html lang="en"> <head> </head> <body> <h3>Javascript Add Array of Object</h3> <table id="productTable"> <thead> <tr> <th>Product Name</th> <th>Price</th> </tr> </thead> <tbody> </tbody> <tfoot> <tr> <th>Total:</th> <th id="totalPrice"></th> </tr> </tfoot> </table> <script> document.addEventListener('DOMContentLoaded', function () { let arrayOfProducts = [ { productName: "iPhone 13", price: 999 }, { productName: "Samsung Galaxy S21", price: 899 }, { productName: "iPad Pro", price: 1099 }, { productName: "MacBook Pro", price: 1799 }, { productName: "iPhone 13", price: 999 }, { productName: "Samsung Galaxy S21", price: 899 } ]; // Function to populate the table with product data and calculate total price function populateTable() { let tableHTML = ''; let totalPrice = 0; arrayOfProducts.forEach(product => { tableHTML += ` <tr> <td>${product.productName}</td> <td>$${product.price}</td> </tr> `; totalPrice += product.price; }); let tbody = document.querySelector('#productTable tbody'); let totalPriceCell = document.querySelector('#totalPrice'); tbody.innerHTML = tableHTML; totalPriceCell.textContent = '$' + totalPrice; } populateTable(); }); </script> <style> table { border-collapse: collapse; width: 100%; } th, td { border: 1px solid #dddddd; text-align: left; padding: 8px; } th { background-color: #f2f2f2; } </style> </body> </html>