I have 3 input field to calculate price and discount percentage. First field is for regular price. What I am trying to do is : If user changes percentage value, discount price will be calculated (2 decimals) and if user changes the discount price, percentage will be calculated.
At the moment I only succeeded calculating the percentage:
function calculatePrice() {
var percentage = $('input[name=\'percentage\']').val(),
price = $('input[name=\'price\']').val(),
calcPrice = price - ( (price/100) * percentage ),
discountPrice = calcPrice.toFixed(2);
$('input[name=\'discount\']').val(discountPrice);
}
function calculatePerc() {
var discountPrice = $('input[name=\'discount]\']').val(),
price = $('input[name=\'price\']').val(),
calcPerc = (price/100) * (price-discountPrice),
discountPerc = calcPerc.toFixed();
$('input[name=\'percentage\']').val(discountPerc);
}
My html :
<input type="text" name="price" value="1000">
<input type="text" name="percentage" onkeyup="calculatePrice()">
<input type="text" name="discount" onkeyup="calculatePerc()">
Here is my fiddle : https://jsfiddle.net/90bo9okg/
// Reusable helper functions
const calculateSale = (listPrice, discount) => {
listPrice = parseFloat(listPrice);
discount = parseFloat(discount);
return (listPrice - ( listPrice * discount / 100 )).toFixed(2); // Sale price
}
const calculateDiscount = (listPrice, salePrice) => {
listPrice = parseFloat(listPrice);
salePrice = parseFloat(salePrice);
return 100 - (salePrice * 100 / listPrice); // Discount percentage
}
// Our use case
const $list = $('input[name="list"]'),
$disc = $('input[name="disc"]'),
$sale = $('input[name="sale"]');
$list.add( $disc ).on('input', () => { // List and Discount inputs events
let sale = $list.val(); // Default to List price
if ( $disc.val().length ) { // if value is entered- calculate sale price
sale = calculateSale($list.val(), $disc.val());
}
$sale.val( sale );
});
$sale.on('input', () => { // Sale input events
let disc = 0; // Default to 0%
if ( $sale.val().length ) { // if value is entered- calculate the discount
disc = calculateDiscount($list.val(), $sale.val());
}
$disc.val( disc );
});
// Init!
$list.trigger('input');
List price: <input type="number" name="list" value="1000"><br>
Discount: <input type="number" name="disc">%<br>
Sale price: <input type="number" name="sale">
<script src="//code.jquery.com/jquery-3.3.1.min.js"></script>
For those looking for a small, quick, and easy piece of javascript code to calculate percentage and round it:
var percentage = Math.round(((currentValue / goalValue) * 100)) +"%";
It will return "100" when the fraction returns "1".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With