I am trying hard to figure out how to let the user input the number of items they want to add to their cart.
This is a standalone Add to cart button inside a repeater. I want that the number parameter in the addToCart function refers to the number inside the #input2 text box.
Here how my code is written:
$w.onReady( function () {
$w(“#button2”).onClick((event) => { let $item = $w.at(event.context); // Get container scope let selectedProduct = $item(‘#dataset1’).getCurrentItem(); let productId = selectedProduct._id; let number = Number((‘#input2’).text);
$w(‘#shoppingCartIcon1’).addToCart(productId, number)
.then(() => {
// Item added to the shopping cart
console.log(“add product ${productId} success”);
})
. catch ((error) => {
// Catch an error that occurs
console.log(“Error: ${error.stack}”);
});
});
});
As you can see I’ve tried to change the #input2 value or text to a number, but the only one item is added to the cart.
Thank you for your answer, but I am not trying to recreate a cart summary.
My page is a search page where an add to cart button is present and I tried to let the user input a custom quantity to add to their cart.
It’s a new version of the deprecated addToCart() method.
import { cart } from "wix-stores"
$w.onReady(() => {
$w("#button2").onClick(async (event, $item) => {
let selectedProduct = $item("#dataset1").getCurrentItem()
let number = Number($item("#input2").value) //This was wrong before
const productToAdd = [
//Create the product to be added
{
productId: selectedProduct._id, //Product ID
quantity: number, //Quantity
},
]
//Transformed to a AWAIT/ASYNC to be more readable
const addProductToCart = await cart.addProducts(productToAdd)
console.log(addProductToCart) //Test the result
})
})