Prevent to click “Add to Cart” button if specific product not selected - Shopify

半城伤御伤魂 提交于 2021-02-10 14:18:51

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!