Борьба за продукт Auto-Add Y, когда продукт X добавляется в CART (Shopify)Javascript

Форум по Javascript
Ответить Пред. темаСлед. тема
Anonymous
 Борьба за продукт Auto-Add Y, когда продукт X добавляется в CART (Shopify)

Сообщение Anonymous »

Первый пост здесь, поэтому, пожалуйста, дайте мне знать, если я что -то пропустил. Любая помощь будет оценена. (Продукт) < /p>

Возврат (ядро) (вариант) < /li>
refundable (Premium) (вариант) < /li>
Возврат (испытание) (вариант) < /li>
< /ul>
i Want, если вы добавите, становятся участниками, это. Auto добавляет основной вариант связи автоматически к корзине. Cart. < /p>
Я стремлюсь удалить кнопку «Удалить» для продукта связи в корзине, чтобы, если вы удалите «стать участником», он автоматически удаляет продукт связи. Оцените < /p>
фрагмент страницы продукта (я поместил это в пользовательский жидкий раздел на шаблоне «Стать членом». < /p>

Код: Выделить всё

document.addEventListener("DOMContentLoaded", function () {
const bondMap = {
//Format: Become a member variant ID: bond variant id
46531128230137: 46586197672185, // Core
46531128262905: 46586197704953, // Premium
46569399288057: 46586197737721, // Trial
};

const form = document.querySelector('form[action^="/cart/add"]');
if (!form) return;

const variantInput = form.querySelector('input[name="id"]');
if (!variantInput) return;

form.addEventListener("submit", function (e) {
const selectedVariantId = parseInt(variantInput.value);
const bondVariantId = bondMap[selectedVariantId];

if (!bondVariantId) return;

// Prevent the default form submission temporarily
e.preventDefault();

// First, add the main product
fetch("/cart/add.js", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
items: [{ id: selectedVariantId, quantity: 1 }]
}),
})
.then(response => response.json())
.then(data => {
// If main product was added successfully, add the bond
return fetch("/cart/add.js", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
items: [{ id: bondVariantId, quantity: 1 }]
}),
});
})
.then(response => response.json())
.then(data => {
// Redirect to cart or refresh page as needed
window.location.href = '/cart';
})
.catch(err => {
console.error("Failed to add products:", err);
// Fall back to normal form submission
form.submit();
});
});
});

< /code>
и на странице жидкой корзины: < /p>


{% comment %}{% unless item.product.tags contains 'Bond' %}{% endcomment %}

Remove

{% comment %}{% endunless %}{% endcomment %}

{% if item.product.tags contains 'Subscription' %}

document.addEventListener("DOMContentLoaded", function () {
const bondMap = {
46531128230137: 46586197672185, // Core
46531128262905: 46586197704953, // Premium
46569399288057: 46586197737721, // Trial
};

function getLineItemKey(cartItems, variantId) {
const item = cartItems.find(i => i.variant_id === variantId);
return item ? item.key : null;
}

function removeBondIfOrphaned() {
fetch("/cart.js")
.then((res) => res.json())
.then((cart) => {
const items = cart.items;
const variantIds = items.map((i) => i.variant_id);

Object.entries(bondMap).forEach(([membershipId, bondId]) => {
const hasMembership = variantIds.includes(parseInt(membershipId));
const hasBond = variantIds.includes(bondId);

if (!hasMembership && hasBond) {
const bondKey = getLineItemKey(items, bondId);
if (bondKey) {
fetch("/cart/change.js", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
id: bondKey,
quantity: 0,
}),
})
.then(() =>  {
// Refresh cart drawer or reload page
if (typeof refreshCartDrawer === 'function') {
refreshCartDrawer();
} else {
window.location.reload();
}
})
.catch(err => console.error("Failed to remove bond:", err));
}
}
});
})
.catch(err => console.error("Failed to fetch cart:", err));
}

// Listen for Remove button clicks using event delegation
document.addEventListener('click', function(e) {
if (e.target.closest('[on\\:click^="/onLineItemRemove"]')) {
// Delay to allow item removal to process
setTimeout(removeBondIfOrphaned, 1000);
}
});
});

{% endif %}



Подробнее здесь: https://stackoverflow.com/questions/796 ... rt-shopify
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Javascript»