简体   繁体   中英

Calculate and Display % Discount for price classes Javascript

I am looking for help with javascript. We are trying to calculate and display the difference in percentage between a price before discount and a price after discount. The relevant classes are .from_price and .for_price. The prices look like this 160,00 and 130,00.

So we were trying with this code, but is doesn't work:

var price = (Math.round($(".from_price").html())).toString();
var sale = (Math.round($(".for_price").html())).toString();
var korting = (Math.round(((sale - price)/price)*100)).toString();
$("#discount").html("You receive" + korting + "%" + " " + "discount");
}

Thanks so much for your help!

This is because you're using string values to get your discount value. You can transform 160,00 to 160 using parseFloat()

 function getDiscount() { var price = parseFloat($(".from_price").html()); var sale = parseFloat($(".for_price").html()); console.log(price); console.log(sale); var korting = (Math.round(((sale - price)/price)*100)); $("#discount").html("You receive" + korting + "%" + " " + "discount"); }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="from_price">160,00</div> <div class="for_price">130,00</div> <button type="button" onclick="getDiscount()">get discount</button> <div id="discount"></div>

Here is an example:

 var price = +((Math.round($(".from_price").html())).toString()); var sale = +((Math.round($(".for_price").html())).toString()); var korting = (Math.round(((sale - price)/price)*100)).toString(); $("#discount").html("You receive "+ korting + " %discount"); console.log(typeof sale);
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="from_price">100</div> <div class="for_price">50</div> <div id="discount"></div>

Your problem was that you trying to do calculations with strings this doesn't work like you expect. Therefore, I coerced your strings into numbers with the + sign and parentheses. Here is an example:

 const el = document.getElementById('test').innerHTML; console.log(el); console.log(typeof el); const sumString = el + el; console.log(sumString); // the string 10 gets added to another string of 10 and thus forms 1010 const sumNr = parseFloat(el) + +(el); // now the strings are coered to numbers, both parseFloat and +(yourvar) coerce strings to nubmers. console.log(sumNr);
 <div id="test">10</div>

Don't use classnames as element selectors (what if your document contains multiple elements with class .from_price?). Don't depend on innerHTML for your (numeric) values. Using data-attributes for the pricing values gives you full control over it. I'd suggest to use css and a data-attribute to display the discount percentage. Finally, you don't really need jQuery for it.

Here's a simple (html in dutch) snippet to play with

 (() => { const price = +document.querySelector("[data-fromprice]").dataset.fromprice; const sale = +document.querySelector("[data-forprice]").dataset.forprice; const discountPercentage = ((1-(sale/price)) * 100).toFixed(0); document.querySelector("[data-discount]").dataset.discount = discountPercentage; })();
 [data-discount]:before { content: attr(data-discount)'%'; color: red; font-weight: bold; }
 <p>Van <span data-fromprice="160">€160,00</span></p> <p>Voor <span data-forprice="130">€130,00</span>!</p> <p>Uw korting: <span data-discount=""></span></p>

<!Doctype html>
<html>
<body>
    <input id="price">Price
    <br><br>
    <input id="discount">%
    <br><br>
    <button onclick="getPrice()">
Get total
</button>
    <br><br>
    <input readonly id="total">
    <script>
        getPrice = function() {
            var numVal1 = Number(document.getElementById("price").value);
            var numVal2 = Number(document.getElementById("discount").value) / 100;
            var totalValue = numVal1 - (numVal1 * numVal2)
            document.getElementById("total").value = totalValue.toFixed(2);
        }
    </script>
</body>
</html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM