Hello everyone! I’m building a client site so that when a customer adds an object to their cart, they’re immediately redirected to another page (think checkout page) but in my case, I’m bringing them to a bottle-selection page that’s linked through CMS based on the product.
I’m extremely close to achieving the result that I’m hoping for. In-fact, it’s been accomplished before HERE, which I’m currently using as the basis for my code.
For those who don’t wish to visit the link, here is the code:
<script>
function addToCartAndBottles() {
document.getElementById('add-to-cart').click();
}
var buyNow = document.getElementById('buy-now');
buyNow.addEventListener("click", addToCartAndBottles);
</script>
Here’s my problem. There are currently 3 products on the page (linked through CMS), with each add-to-cart button having an id of “add-to-cart” and the Buy Now button with an id of “buy-now”. When the page is published, the first product works - it adds the product to your cart and redirects to the page - but none of the remaining 2.
My own digging has led me to believe that this is happening because the code uses ID’s, instead of classes. REFERENCE . I’ve tried adding classes to my elements and altering the code, but I cannot get it to work. Here’s my attempt at changing to classes, but it stops working all together.
<script>
function addToCartAndBottles() {
document.getElementsByClassName('add-to-cart').click();
}
var buyNow = document.getElementsByClassName('buy-now');
buyNow.addEventListener("click", addToCartAndBottles);
</script>
If anyone has any ideas, you have no idea how much I’d appreciate it! Client project due this week, and it’s the last piece of the puzzle for me haha.
Thanks a lot for your response! I might not have explained my goal properly. I’m not trying to add all 3 bottles at once, but rather, when the button is clicked, it adds whatever product you selected to the cart, and redirects you to the respective CMS-page for that product. It currently works for one of the pages, but not for the remaining 2 items in the collection.
Here’s a video explaining what I’m trying to accomplish:
What else can I provide to have this post replied to? Client project is due tomorrow night and I’d really appreciate it if someone could help me fix this code! thanks!
I also realized that using this method was not the best workflow considering I previously nested the products inside of the “VIP Sections” CMS collections (there were nine on each page, with 3 experience options for each one, resulting in 27 product ID’s). To fix this solution, I changed the structure to include a VIP Section booking option, which will add the product to your cart for the designated time slot then redirect you to the generic experiences page. That way I would only need 3 ID tags.