Итак, у меня есть гравитационная форма, в которой хранятся цены и переменные продукта. У меня есть код, так что при количестве 3 или более он начинает снижать цену за длину и общую цену, однако цена со скидкой за длину и общая цена со скидкой отображаются только в течение секунды, прежде чем она возвращается обратно к цене без скидки.
URL-адрес, по которому вы можете увидеть это: https://wordpress-714066-4065525.cloudw ... m-bunting/
Итак, я попробовал. Код расчета цены необходимо продублировать в функции мутации создания общей цены.
Мой код:
//Get Custom Quantity Field
const customQuanityField = document.querySelector('.gfield--type-number input');
customQuanityField.value = 1;
//Get the default Quantity Field
const defaultQuanityField = document.querySelector('input[name="quantity"]');
defaultQuanityField.parentElement.setAttribute('style', 'display: none');
//defaultQuanityField.disabled = true;
let isProgrammaticChange = false;
defaultQuanityField.addEventListener('change', (e) => {
if (isProgrammaticChange) {
isProgrammaticChange = false;
return;
}
const quantity = e.target.value;
isProgrammaticChange = true;
customQuanityField.value = quantity;
});
customQuanityField.addEventListener('change', (e) => {
if (isProgrammaticChange) {
isProgrammaticChange = false;
return;
}
const quantity = e.target.value;
isProgrammaticChange = true;
defaultQuanityField.value = quantity;
});
//
//
//Custom Bunting Update price to read £xx.xx per car flag
//
//
// Select the node that will be observed for mutations
const dynamicPriceEl = document.querySelector('.product_totals ul > li:last-of-type > div');
const perFlagTextEl = document.createElement('p');
perFlagTextEl.textContent = ' per length';
perFlagTextEl.classList.add('per-length-text');
dynamicPriceEl.appendChild(perFlagTextEl);
// Options for the observer (which mutations to observe)
const config = { attributes: false, childList: true, subtree: true };
// Callback function to execute when mutations are observed
const createTotalPrice = (mutationList, observer) => {
console.log('createTotalPrice');
for (const mutation of mutationList) {
if (mutation.type === "childList") {
const target = mutation.target;
const splitPrice = target.innerHTML.split('').slice(1).join('');
const calculatedPrice = parseFloat(splitPrice);
const totalPrice = (customQuanityField.value * calculatedPrice).toFixed(2);
console.log('totalPrice', totalPrice);
const totalPriceCalculation = document.querySelector('.total-calculated-price');
if(totalPriceCalculation) {
totalPriceCalculation.textContent = totalPrice;
} else {
const totalPriceCalculationEl = document.createElement('p');
totalPriceCalculationEl.classList.add('total-calculated-price');
totalPriceCalculationEl.textContent = totalPrice;
target.parentElement.after(totalPriceCalculationEl)
}
//console.log(`The new list has ${mutation.addedNodes[0].children[0].childElementCount} chilren.`);
}
}
};
// Create an observer instance linked to the callback function
const createTotalPriceObserver = new MutationObserver(createTotalPrice);
// Start observing the target node for configured mutations
createTotalPriceObserver.observe(dynamicPriceEl, config);
window.addEventListener('load', () => {
console.log('Script initialized');
// DOM Elements
const customQuanityField = document.querySelector('.gfield--type-number input');
const formattedTotalPrice = document.querySelector('.formattedTotalPrice');
const dynamicPriceEl = document.querySelector('.product_totals ul > li:last-of-type > div');
const gformPrice = document.querySelector('.ginput_product_price');
const gformTotal = document.querySelector('.ginput_total');
function updatePriceDisplay(quantity) {
if (!originalUnitPrice || isUpdating) return;
isUpdating = true;
try {
const discount = getDiscount(quantity);
const discountedUnitPrice = originalUnitPrice * (1 - discount / 100);
const total = discountedUnitPrice * quantity;
console.log('Calculating prices:', {
originalPrice: originalUnitPrice,
quantity,
discount,
discountedUnit: discountedUnitPrice,
total
});
// Update Gravity Forms price field and trigger recalculation
if (gformPrice) {
gformPrice.value = discountedUnitPrice.toFixed(2);
// Trigger multiple events to ensure Gravity Forms updates
gformPrice.dispatchEvent(new Event('change', { bubbles: true }));
gformPrice.dispatchEvent(new Event('keyup', { bubbles: true }));
// Force Gravity Forms to recalculate
if (window.gformCalculateTotalPrice) {
window.gformCalculateTotalPrice(1); // Assuming form ID is 1
}
// Update quantity field if it exists
const quantityInput = document.querySelector('input[name="quantity"]');
if (quantityInput) {
quantityInput.value = quantity;
quantityInput.dispatchEvent(new Event('change', { bubbles: true }));
}
}
// Update message
let messageEl = document.querySelector('.add-more-message');
if (!messageEl) {
messageEl = document.createElement('p');
messageEl.classList.add('add-more-message');
customQuanityField.after(messageEl);
}
messageEl.textContent = quantity < 3
? `Add ${3 - quantity} more to your basket to qualify for a 2.5% discount to this item.`
: `You're currently getting ${discount}% off this item.`;
// Force update total display
if (gformTotal) {
const newTotal = total.toFixed(2);
if (gformTotal.textContent !== `£${newTotal}`) {
gformTotal.textContent = `£${newTotal}`;
}
}
} finally {
isUpdating = false;
}
}
});
}
Подробнее здесь: https://stackoverflow.com/questions/792 ... rice-a-sec
Почему на секунду отображается цена со скидкой, а через секунду — полная цена? ⇐ Php
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Почему на секунду отображается цена со скидкой, а через секунду — полная цена?
Anonymous » » в форуме Php - 0 Ответы
- 38 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Почему на секунду отображается цена со скидкой, а через секунду — полная цена?
Anonymous » » в форуме Php - 0 Ответы
- 32 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Как разрешить код купона с индивидуальной скидкой на товары со скидкой в Woocommerce?
Anonymous » » в форуме Php - 0 Ответы
- 86 Просмотры
-
Последнее сообщение Anonymous
-