How to make Add to cart button add 2 products to the cart

styleshop27
Shopify Partner
30 0 2

Is there a simple way of making the add to cart button on a product page add 2 items? I have a checkbox on my product page, and when it is checked, I want to add the main product as well as the upsell (the checkbox product) to the cart. I am familiar with adding custom code. 

 

I tried adding an event listener to the add to cart button when the upsell checkbox is clicked, which then listens for the ATC button click, then does a fetch to add the upsell product to the cart, but it is not working and I am unsure why. 

 

The fetch within the function does work if I do it when the checkbox is clicked, rather than when ATC is clicked, which I found strange. Optimally I would like to do it when ATC is clicked, as shown below in the function: 

 

EDIT: the function works but only when I created a dummy button to test it with, when I use the product ATC button to trigger the function on click, I get this error in console:

TypeError: Cannot read properties of null (reading 'innerHTML')
    at CartNotification.getSectionInnerHTML

 

Function:

 

function watchATC() {
      var button = document.getElementById("button");
      button.addEventListener("click", function(event){
        const cartNotification = new CartNotification();
        if (document.getElementById('screen-protector-upsell').checked) {
        const config = fetchConfig('javascript');
        config.headers['X-Requested-With'] = 'XMLHttpRequest';
        config.body = JSON.stringify({
          id: protector,
          sections: cartNotification.getSectionsToRender().map((section) => section.id),
          sections_url: window.location.pathname
        });     
        fetch(`${routes.cart_add_url}`, config)
          .then((response) => response.json())
          .then((response) => {
            cartNotification.renderContents(response);
            this.window.SLIDECART_UPDATE(response);
        })
        .catch((e) => {
          console.error(e);
        });
        } 
      });  
    }

 

 

 

 

Replies 0 (0)