问题
Hi experts have a nice day, I have a project on Shopify where I'm getting struggled on how to prevent and make alert when a specific product selected for some conditions.
I made a product template where I populate list of products from collection A as a first set of selection and collection B as a second set of selection.
This is a product page where I can select 1 product from collection A and also 1 product from collection B (Each product has Add to Cart button)
The condition is collection A is required to have a least 1 product added from collection B while collection B does not required to have product from collection A.
Here is I wan't to achieve: when either products from collection A button clicked it will alert like "Need to select at least 1 product from collection B"
I'm using cart.js for the multiple products in a product template. Is this possible? or is there's a simplest way to implement this?
Thanks
回答1:
I can't speak to the inner workings of cart.js
, but what you're asking for should be reasonably straightforward with regular Javascript.
What it sounds like you want to do is:
- On submit of Form A;
- Select Form B;
- Check if Form B has a variant selected;
- Prevent the add-to-cart action if no variant in Form B
If cart.js
has an easy way to insert a validation function, that's where I would insert the code. Otherwise, I would add the validation function to the form submit or click of the submit button, whichever is more convenient with cart.js
being in play.
A sample validation function would look something like:
function validateFormA(evt){
var formB = document.forms('product-form-b'); // document.forms can access any form on the page using the appropriate ID attribute
if(!form){
// Couldn't find form, should this pass or fail?
return;
}
var variantIdField = form.id; // To access the form control with the name 'id'
var value = variantIdField.value;
if(!value){
evt.preventDefault();
return false;
}
return true;
}
来源:https://stackoverflow.com/questions/50709823/prevent-to-click-add-to-cart-button-if-specific-product-not-selected-shopify