I'm creating a way to add all the products in a Shopify collection to the cart as a way to sell bundles.
I have a JavaScript script that determines which level of kit is selected, and loops through each product in the collection. A few products in the bundle we want added more than once, and these are controlled by the tag basicbundleqty:x. So the code loops through the tags for each product, checks for this tag, and if it has it then the qty is set to the suffix of the tag.
<script>
var selected = "not selected";
function kitSelect(){
selected = document.getElementById('select').value;
/*if(selected == "not selected"){
alert('Please select a kit level');
}
if(selected == "basic"){
alert('basic');
}
if(selected == "standard"){
alert('standard');
}
if(selected == "pro"){
alert('pro');
}*/
}
function addBundle(){
var qty = 0;
if(selected == "basic"){
{% for kitproduct in collections['Basic-Fixture-Plate-Starter-Kit'].products %}
qty = 1;
{% for t in kitproduct.tags %}
{% if t contains 'basicqty:' %}
{% assign qty = t | remove: 'basicqty:'%}
{% assign qty = qty | plus: 0 %}
qty = {{ qty | json }};
{% endif %}
{% endfor %}
jQuery.post('/cart/add.js', {
quantity: qty,
id: {{ kitproduct.variants[0].id }},
properties: {
}
});
alert(qty);
{% endfor %}
} else {
alert("Please select a kit level first");
}
window.location.reload(false);
}
</script>
This method does work, with one quirk. without the line alert(qty);
at the end of the for loop, the code does not work. If that alert is not there, the code will seemingly randomly add just one or two of the collection products.
Why does this only work with the alert()
function, and is there a fix that will allow this to add them all to cart with one click and not require the user clicking through each alert window?