Would like help setting multiple cookies for multiple dynamic divs.
I am able to set 1 cookie for 1 div, but, when I add more than 1 item/div to the cart, the cookies are only getting set on the first child/div.
The number of divs being added to the cart will always be unknown and dynamically generated... how can I create unique cookies for each of the cart items being added?
Thank you so much for your time & help! any help would be greatly appreciated, Steve.
CODE AVAILABLE HERE
$('#bag_active').on('click', '.add-to-cart', function setCookie() {
alert("COOKIES SET");
var customObject = {};
customObject.name = document.getElementById("cart_product_name").value;
customObject.price = document.getElementById("cart_product_price").value;
var jsonString = JSON.stringify(customObject);
document.cookie = "cookieObject=" + jsonString;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div id="bag_active" class="product-card">
<h1 class="title">Cookie Title 1</h1>
<h2 class="subtitle">Cookie Price 1</h2>
<button id="1" type="button" class="btn add-to-cart" aria-pressed="true" onclick="setCookie()">Add to Bag</button>
<input type="hidden" id="cart_product_name" name="Cookie Name 1" value="Cookie Name 1">
<input type="hidden" id="cart_product_price" name="Cookie Price 1" value="Cookie Price 1">
</div>
<div id="bag_active" class="product-card">
<h1 class="title">Cookie Title 2</h1>
<h2 class="subtitle">Cookie Price 2</h2>
<button id="2" type="button" class="btn add-to-cart" aria-pressed="true" onclick="setCookie()">Add to Bag</button>
<input type="hidden" id="cart_product_name" name="Cookie Name 2" value="Cookie Name 2">
<input type="hidden" id="cart_product_price" name="Cookie Price 2" value="Cookie Price 2">
</div>
<div id="bag_active" class="product-card">
<h1 class="title">Cookie Title 3</h1>
<h2 class="subtitle">Cookie Price 3</h2>
<button id="3" type="button" class="btn add-to-cart" aria-pressed="true" onclick="setCookie()">Add to Bag</button>
<input type="hidden" id="cart_product_name" name="Cookie Name 3" value="Cookie Name 3">
<input type="hidden" id="cart_product_price" name="Cookie Price 3" value="Cookie Price 3">
</div>
I'd assume you rewrite your click handler to something like: