<h2>Products</h2>
<div class="products"></div>
<h2>Cart</h2>
<div class="cart"></div>
.product {
background: #AA88FF;
padding: .5em;
color: white;
margin: 1em;
}
View Compiled
let products = [
{
name: 'Product 1',
selected: true,
price: 10.5,
},
{
name: 'Product 2',
selected: false,
price: 4.5,
},
{
name: 'Product 3',
selected: false,
price: 5,
},
]
let $ = document.querySelector.bind(document)
let $$ = document.querySelectorAll.bind(document)
function getProductHTML(product, index) {
return `
<div class="product product-${index}">
<div class="product-info">${product.name} - ${product.price} $</div>
<input type="checkbox" ${product.selected ? 'checked' : ''}>
</div>
`
}
function refreshProducts() {
$('.products').innerHTML = products.map(getProductHTML).join(' ')
products.map((product, index) => {
$(`.product-${index}`).addEventListener('input', event => {
product.selected = event.target.checked
refreshProducts()
setCartHTML()
})
})
}
function setCartHTML() {
$('.cart').innerHTML = products
.filter(product => product.selected)
.map(product => `<div class="product">${product.name}</div>`)
.join('')
}
refreshProducts()
setCartHTML()
View Compiled
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.