This page looks best with JavaScript enabled

how to update product total prices discount based on unit number

 ·  ☕ 2 min read  ·  👽 john hashim

This snipet is for anyone building a wholesale woo-commerce site that sale products in large amount and offer discount based on the the number of units bought. for instance if 10 units will eaqual to 200$ then 20 units will equal to 392$ and so on …

You can try to tweak this simple code based on your your Woorcommerce theme.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
var price = parseFloat(someVars['regularPrice']);
var discountTable = [];

someVars.discounts.forEach(function (el) {
    discountTable.push({ min: parseFloat(el.min), max: parseFloat(el.max), discount: parseFloat(el.discount) });
})

var sortedTable = discountTable.sort(function (a, b) {
    return a.min - b.min;
})

sortedTable.unshift({ min: 1, max: sortedTable[0].min - 1, discount: 0 });
sortedTable.length
sortedTable[sortedTable.length - 1].max = Infinity

// Calc full price
function calcPrice(qty) {
    for (i = 0; i < sortedTable.length; i++) {
        if (qty >= sortedTable[i].min && qty <= sortedTable[i].max) {
            return Math.round((qty * (price - sortedTable[i].discount)) * 100) / 100;
        }
    }
}

console.log(calcPrice(7))

// Add event listener for qty to change in form

// alternative to DOMContentLoaded
document.addEventListener("DOMContentLoaded", function () {
    // Initialize your application or run some code.

    selectElement = document.querySelector('input.qty');
    selectElement.addEventListener('change', qtyChanged);
    plusElement = document.querySelector('input.plus');
    plusElement.addEventListener('click', qtyChanged);
    minusElement = document.querySelector('input.minus');
    minusElement.addEventListener('click', qtyChanged);


})

function qtyChanged() {
    setTimeout(function () {
        console.log(calcPrice(selectElement.value));
        // Update the innerText of the price element to reflect new total

        document.querySelector('.product-price').innerText = 'PRICE $ : ' + calcPrice(selectElement.value)
    }, 001)

}

Thanks and hope this works for you .

Share on

john hashim
WRITTEN BY
john hashim
Web Developer