You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

自定义彩旗产品页面折扣价格短暂显示后恢复原价的问题求助

自定义彩旗产品页面折扣价格短暂显示后恢复原价的问题求助

Hey folks, I'm stuck with a frustrating issue on my custom bunting product page that uses Gravity Forms. Let me break it down:

I've written code that's supposed to apply a discount when the quantity hits 3 or more—both the per-length unit price and the total price should update to reflect the discounted amounts. But right now, those discounted values only flash on the screen for a split second before reverting back to the original non-discounted prices.

I tried moving the price calculation logic into the createTotalPrice mutation observer function, but that didn't fix the problem.

Here's the full code I'm working with:

//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;
        }
    }

});
}

</script>

Has anyone run into this kind of issue with Gravity Forms before? I feel like I'm missing something with how the mutation observer or Gravity Forms' internal recalculation is firing. Any pointers would be really appreciated!

备注:内容来源于stack exchange,提问作者Alex McIver

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 16:23:02