addToCart custom quantity via user input

Hi,

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.

How can I make this work?

Thank you

https://www.vorbly.com/Vorbly-Code/WIX-REPEATER-SUM-TOTAL-OF-ALL-ITEMS
https://www.vorbly.com/Vorbly-Code/WIX-CODE-CALCULATIONS—SUM-NUMBERS
https://www.vorbly.com/Vorbly-Code/WIX-CODE-CALCULATIONS—MULTIPLY-NUMBERS

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.


As you can see in the screenshot the text box written 3 would be the quantity added when clicked on “Ajouter au Panier”(add to cart).

Thank you

Did you found out how to code it? I am trying to do the same thing

Hello, can you try this code?

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
    })
})