Почему на секунду отображается цена со скидкой, а через секунду — полная цена?Php

Кемеровские программисты php общаются здесь
Ответить Пред. темаСлед. тема
Anonymous
 Почему на секунду отображается цена со скидкой, а через секунду — полная цена?

Сообщение Anonymous »

Итак, у меня есть гравитационная форма, в которой хранятся цены и переменные продукта. У меня есть код, который при количестве 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;
}
}

});
}


Мои проблемы удалось решить с помощью следующего кода:

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

// Remove the discount from the price to get the true base price
const price = parseFloat(priceText.replace(/[^0-9.]/g, ''));
const quantity = parseInt(customQuanityField.value) || 1;

// Find current discount if any
let currentDiscount = 0;
for (const range in productDiscounts) {
const [min, max] = range.split(' - ').map(Number);
if (quantity >= min && quantity 

Подробнее здесь: [url]https://stackoverflow.com/questions/79260643/why-does-the-discount-price-show-for-a-second-and-then-show-the-full-price-a-sec[/url]
Реклама
Ответить Пред. темаСлед. тема

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

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

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

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

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

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