Files
test/tugas/javascriptngelu.js
2026-10-29 09:32:18 +07:00

62 lines
1.8 KiB
JavaScript

let cart = [];
const cartItemsContainer = document.getElementById('cart-items');
const cartTotalElement = document.getElementById('cart-total');
const emptyCartMsg = document.getElementById('empty-cart-msg');
const addButtons = document.querySelectorAll('.add-to-cart-btn');
addButtons.forEach(button => {
button.addEventListener('click', function() {
const name = this.getAttribute('data-name');
const price = parseFloat(this.getAttribute('data-price'));
cart.push({ name, price });
renderCart();
});
});
cartItemsContainer.addEventListener('click', function () {
if (event.target.matches('.remove-btn') || event.target.closest('.remove-btn')) {
const itemIndex = event.target.getAttribute('data-index');
cart.splice(itemIndex, 1);
renderCart();
}
});
function renderCart() {
cartItemsContainer.innerHTML = '';
let total = 0;
if (cart.length === 0) {
emptyCartMsg.style.display = 'block';
} else {
emptyCartMsg.style.display = 'none';
cart.forEach((item, index) => {
total += item.price;
const li = document.createElement('li');
li.className = 'flex justify-between items-center bg-gray-50 p-2 rounded border';
const span = document.createElement('span');
// Mengubah format harga menjadi style Rupiah (id-ID)
span.textContent = `${item.name} - Rp ${item.price.toLocaleString('id-ID')}`;
const removeBtn = document.createElement('button');
removeBtn.textContent = 'Remove';
removeBtn.className = 'remove-btn bg-red-500 text-white px-2 py-1 rounded text-sm hover:bg-red-600';
removeBtn.setAttribute('data-index', index);
li.appendChild(span);
li.appendChild(removeBtn);
cartItemsContainer.appendChild(li);
});
}
cartTotalElement.textContent = total.toLocaleString('id-ID');
}