Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

theUnforgiven's avatar

jQuery help - pricing & discounts

Hi all,

Hope everyone has had a good week.....

My question comes in the form of I'm trying to get one figure the minus another figure. I'm using jQuery for this has I haven't got around to re-learning Vue just yet.

So lets say I have a figure of $27.99 then the customer applies a discount code of $5 that would equal $22.99 right? Based on this (slightly messy hack) where am I going wrong?

$("#success").hide();
$("#error").hide();
var totalPrice = $("#totalPricePHP").text().replace("£", "").replace(".", "");

$("#validateCoupon").click(function(e) {
    e.preventDefault();
    $.ajax({
        type: "POST",
        url: '/validateCoupon/' + $('#coupon').val(),
        data: {
            code: $('#coupon').val()
        },

        success: function(data) {
            console.log("Total: " + totalPrice);
            console.log("Discount: " + data.amount);

            if (data != '') {
                $("#error").hide();
                $("#totalPricePHP").hide();
                $("#success").show().append("Great! £" + data.amount + " has been deducted.");
                $("#success:disabled");
                $("#totalPrice").html("£" + Math.round(data.amount - totalPrice));
            }
        },
        error: function(data){
            console.log(data);
            $("#success").hide();
            $("#error").show().append("Something was wrong with the coupon you entered.");
        }

    });
});

Idea's to improve this messy lot, will also be grateful, but just looking to get it working and formatting in a currency correctly first.

0 likes
6 replies
erikverbeek's avatar

Shouldn't it be totalPrice - data.amount instead of the other way round?

Also, I asume you are doing the actual calculation of the price on the server? Otherwise someone can alter the price in the browser. So why not send the discounted amount back instead of recalculating it client side?

1 like
theUnforgiven's avatar

So I managed to get it working to some extent by doing the following:

var discount = data.amount * 100 / 100;
var discountedTotal = totalPrice - discount;
$("#totalPrice").html("£" + parseFloat(discountedTotal));

This shows 10% from the original price. Which shows as 2790 so I need to put a . in there for the decimal place, I've tried .toFixed(2) but to no avail. Anyone have have suggestions?

willvincent's avatar
Level 54
$("#totalPrice").html("£" + parseFloat(discountedTotal / 100).toFixed(2));
1 like

Please or to participate in this conversation.