gpt4 book ai didi

jquery - 按值(value)计算百分比或按百分比计算值(value)

转载 作者:行者123 更新时间:2023-12-01 00:51:08 24 4
gpt4 key购买 nike

我有 3 个输入字段来计算价格和折扣百分比。第一个字段是正常价格。我想做的是:如果用户更改百分比值,将计算折扣价格(2 位小数),如果用户更改折扣价格,将计算百分比。

目前我只成功计算了百分比:

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);
}

我的html:

<input type="text" name="price" value="1000">
<input type="text" name="percentage" onkeyup="calculatePrice()">
<input type="text" name="discount" onkeyup="calculatePerc()">

这是我的 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>

关于jquery - 按值(value)计算百分比或按百分比计算值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35759408/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com