So I have a gravity form that stores prices and the product variables. I have the code so that when a quantity of 3 or more it starts discounting the price per length and the total price however the discounted price per length and the total discounted price only show for a second before it reverts back to the non discounted price.
The URL you can see this on is https://wordpress-714066-4065525.cloudwaysapps.com/product/custom-bunting/
So I have tried Price calculation code needs to be duplicated in create total price mutation function
My code is
//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>
// 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 <= max) {
currentDiscount = productDiscounts[range];
break;
}
}
// Return the original base price by removing the discount
return price / (1 - currentDiscount / 100);