Adding custom conditional logic for 'add-on' products

Topic summary

A Shopify store owner is attempting to implement custom conditional logic to prevent ‘secondary’ (add-on) products from being added to the cart unless a ‘primary’ product is already present. This functionality isn’t natively available in Shopify’s Crave theme, and the user wants to avoid purchasing a third-party app.

Current approach:

  • Using AI-generated JavaScript code that defines primary and secondary product IDs
  • Code checks cart contents via fetch API before allowing secondary product additions
  • Displays custom success/error messages to users

Technical issue:
The provided code appears corrupted or reversed in the latter portion, making it difficult to parse. A respondent (Discount-Bot) suggests that preventDefault() may not work reliably when attaching event listeners directly to forms.

Proposed solution:
Change the query selector from targeting the form element to directly targeting the “Add to Cart” button (.product-form__submit button) to ensure the default form submission is properly prevented.

Status: The discussion remains open with troubleshooting in progress.

Summarized with AI on November 8. AI used: claude-sonnet-4-5-20250929.

Hello,

I am trying to create custom code to prevent products which are tagged as ‘secondary’ from being added to the cart without a ‘primary’ tagged product already in the card. This is in Shopify Crave theme.

I had really hoped this simple feature was included in Shopify but alas, another costly plug-in app may be required…

My store url is nativeangusbeef.com.au

Here is the code I am generating from AI:

I am testing by adding a secondary item to an empty card. While an error message appears, the form submission still proceeds and the ‘secondary’ item is still added to the cart, despite there being no primary item.

Thank you for any assistance you can provide.

I’ve noticed that the preventDefault() does not seem to work sometimes if you add the event listener to the form directly.

Try changing your query selector to select the “Add to Cart” button directly like this:

document.querySelector(‘button.product-form__submit’)

Correspondingly, your form data should be available here:

const form = event.target.form;