Tengo el siguiente código javascript, con las dos primeras funciones y la cantidad en la primera variable hacia la parte inferior siendo la más importante aquí:
// show qty and price function add(qty) { qty++; document.getElementById("qty").innerHTML = (qty); } function remove(qty) { if (qty > 0) { qty--; document.getElementById("qty").innerHTML = (qty); } else { document.getElementById("qty").innerHTML = (qty); } } // load products on home function bl() { document.getElementById("bl").style.display = "initial"; document.getElementById("br").style.display = "none"; } function br() { document.getElementById("br").style.display = "initial"; document.getElementById("bl").style.display = "none"; } // load cart function cart() { document.getElementById("cart").style.display="block"; if (qty == 0) { document.getElementById("by").style.display="none"; } else { document.getElementById("by").style.display="block"; } } // leave cart function leavecart() { document.getElementById("cart").style.display="none"; } // product list var flower = { blueyellow: { color : "linear-gradient(to right, blue, yellow)", src : "https://cdn.pixabay.com/photo/2022/07/22/15/11/woman-7338352_1280.jpg", price : 30, qty : 0, size : "small" }, redyellow: { color : "red, yellow", src : "https://cdn.pixabay.com/photo/2022/05/22/16/50/outdoors-7213961_1280.jpg", price : 25, qty : 0, size : "large" } }; // product list in cart document.getElementById("bycolor").style.display = (flower.blueyellow.color); document.getElementById("bysrc").src = (flower.blueyellow.src); document.getElementById("byprice").innerHTML = ("$" + flower.blueyellow.price);Luego tengo dos botones: uno para agregar a la cantidad y otro para eliminar de la cantidad:
<div id="wrap" style="padding: 10px;"> <h2>Add to Cart</h2><p id="qty"></p><button onclick="add(flower.blueyellow.qty)">+</button><button onclick="remove(flower.blueyellow.qty)">-</button> </div>El problema aquí es que onclick solo lleva la cantidad a 1 y no más. Lo tenía funcionando antes de intentar adaptarlo a una variable dentro de una variable, pero ahora se detiene.
Es porque no está aumentando el valor real de flower.blueyellow.qty
function add(color) { flower[color].qty++ document.getElementById("qty").innerHTML=flower[color].qty; } function remove(color) { if (flower[color].qty > 0) { flower[color].qty-- document.getElementById("qty").innerHTML = flower[color].qty; } else { document.getElementById("qty").innerHTML = flower[color].qty; } } var flower = { blueyellow: { color : "linear-gradient(to right, blue, yellow)", src : "https://cdn.pixabay.com/photo/2022/07/22/15/11/woman-7338352_1280.jpg", price : 30, qty : 0, size : "small" }, }; <div id="wrap" style="padding: 10px;"> <h2>Add to Cart</h2><p id="qty"></p><button onclick="add('blueyellow')">+</button><button onclick="remove('blueyellow')">-</button> </div>