1

Trying to recalculate the final price in JS after applying a discount, but doesn’t seem to work. Total Cart and Redeem Coupon function just fine, but I can’t get the final price.

// TOTAL CART
obj.totalCart = function () {
   var totalCart = 0;
   for (var item in cart) {
      totalCart += cart[item].price * cart[item].count;
   }   return Number(totalCart.toFixed(2));
}

// REDEEM COUPON
function validate(discount) {
   var disc = "WE56DQ1";
   var coupon = disc.trim();
   var input = document.getElementById('discount').value;
   if (input.toUpperCase() == coupon.toUpperCase()) {
      document.getElementById('message').innerHTML = "Discount applied!";
      document.getElementById('err').innerHTML = "";
      return true;
   } else {
      document.getElementById('err').innerHTML = "Invalid discount";
      document.getElementById('message').innerHTML = "";
      return false;
   }
}

// FINAL PRICE AFTER COUPON
obj.totalPrice = function () {
   var discount = 20;
   return totalPrice = totalCart - (totalCart * discount / 100);
}
Ezekiel
  • 11
  • 2
  • Please format your code properly, and add an example of the erroneous and your expected output. – Fabian Zeindl Aug 01 '20 at 13:53
  • The desired output is the final price after the discount is applied, which is not displayed at all. Thought of turning Final Price into a if statement, if discount is applied then ```"totalPrice = Math.floor((totalCart/100)*(100-discount))``` else newprice = totalCart, but the code for this escapes me. – Ezekiel Aug 02 '20 at 14:34

1 Answers1

1

To do this you could simply try:

newprice = Math.floor((oldprice/10)*80)

or

newprice = Math.floor((oldprice/100)*(100-discount))

Thanks for taking the time to make a post.

However, if you are planning to make this into a shop, it would be best to do all of the calculations on the server unless the js is server-side.

  • thanks for the quick answer. Thought of turning newprice into a if else statement condition, if the discount is applied, then "newprice = Math.floor((oldprice/10)*80)" else newprice = totalCart, but the code for this escapes me. Thanks) – Ezekiel Aug 02 '20 at 10:46