ejercicio 8: carrito de compras
This commit is contained in:
@@ -1 +1,71 @@
|
||||
// Agregar aquí el código javascript
|
||||
const productos = [
|
||||
{ nombre: "Teclado", precio: 8500 },
|
||||
{ nombre: "Mouse", precio: 4200 },
|
||||
{ nombre: "Monitor", precio: 62000 },
|
||||
{ nombre: "Auriculares", precio: 11000 },
|
||||
{ nombre: "Webcam", precio: 15500 }
|
||||
];
|
||||
|
||||
const contenedorProductos = document.querySelector("#productos");
|
||||
const carritoLista = document.querySelector("#carrito");
|
||||
const totalTexto = document.querySelector("#total");
|
||||
|
||||
const carrito = [];
|
||||
|
||||
function mostrarProductos() {
|
||||
for (const producto of productos) {
|
||||
const div = document.createElement("div");
|
||||
|
||||
div.innerHTML = `
|
||||
<span>${producto.nombre} - $${producto.precio}</span>
|
||||
<button>Agregar al carrito</button>
|
||||
`;
|
||||
|
||||
const boton = div.querySelector("button");
|
||||
|
||||
boton.addEventListener("click", () => {
|
||||
agregarAlCarrito(producto);
|
||||
});
|
||||
|
||||
contenedorProductos.appendChild(div);
|
||||
}
|
||||
}
|
||||
|
||||
function agregarAlCarrito(producto) {
|
||||
const existente = carrito.find(
|
||||
item => item.nombre === producto.nombre
|
||||
);
|
||||
|
||||
if (existente) {
|
||||
existente.cantidad++;
|
||||
} else {
|
||||
carrito.push({
|
||||
nombre: producto.nombre,
|
||||
precio: producto.precio,
|
||||
cantidad: 1
|
||||
});
|
||||
}
|
||||
|
||||
actualizarCarrito();
|
||||
}
|
||||
|
||||
function actualizarCarrito() {
|
||||
carritoLista.innerHTML = "";
|
||||
|
||||
let total = 0;
|
||||
|
||||
for (const item of carrito) {
|
||||
const li = document.createElement("li");
|
||||
|
||||
li.textContent =
|
||||
`${item.nombre} x${item.cantidad} - $${item.precio * item.cantidad}`;
|
||||
|
||||
carritoLista.appendChild(li);
|
||||
|
||||
total += item.precio * item.cantidad;
|
||||
}
|
||||
|
||||
totalTexto.textContent = `Total: $${total}`;
|
||||
}
|
||||
|
||||
mostrarProductos();
|
||||
|
||||
@@ -8,7 +8,15 @@
|
||||
</head>
|
||||
<body>
|
||||
<h1>Ejercicio 8</h1>
|
||||
<h1>Productos</h1>
|
||||
|
||||
<div id="productos"></div>
|
||||
|
||||
<h2>Carrito</h2>
|
||||
|
||||
<ul id="carrito"></ul>
|
||||
|
||||
<p id="total">Total: $0</p>
|
||||
<script src="ejercicio8.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
Reference in New Issue
Block a user