我正在做一个折扣功能,用户可以输入折扣金额,例如如果用户输入10则变为50(商品价格)-10=40,如果用户输入10%,结果是50-10%=45 。
我尝试过以下代码。值是否包含 % 符号可能有所不同,但如果包含则值变为 NaN。我知道它在计算时无法识别该符号,因此它变成 NaN,但如何使其忽略 % 符号?当我输入折扣时它也会改变。 谢谢。
$("#table_invoice").on("input", '.dt_discount', function() {
calculate_subTotal($(this).closest('.dt_row'));
})
function calculate_subTotal(row) {
var unitCost = $(row).find(".dt_unitPrice").val();
var qty = $(row).find(".dt_qty").val();
var discount = $(row).find(".dt_discount").val();
if (discount.indexOf("%") > -1) {
var row_total = Number(unitCost * qty * (1 - (discount / 100)));
} else {
var row_total = Number((unitCost * qty) - discount);
}
$(row).find(".dt_subtotal").val(row_total);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="table_invoice">
<row class="dt_row">
Price<input class="form-control form-price dt_unitPrice" name="dt_unitPrice" value="50"></br>
Qty<input class="form-control form-quantity dt_qty" name="dt_qty" value="2"></br>
Discount<input class="form-control form-discount dt_discount" name="dt_discount" value="0"></br>
Total<input class="form-control form-price dt_subtotal" name="dt_subtotal" value="0.00">
</row>
</div>
最佳答案
如果折扣包含百分比,则可以解析折扣。
$("#table_invoice").on("input", '.dt_discount', function() {
calculate_subTotal($(this).closest('.dt_row'));
})
function calculate_subTotal(row) {
var unitCost = $(row).find(".dt_unitPrice").val();
var qty = $(row).find(".dt_qty").val();
var discount = $(row).find(".dt_discount").val();
if (discount.indexOf("%") > -1) {
discount = parseInt(discount, 10); // <-- here
var row_total = Number(unitCost * qty * (1 - (discount / 100)));
} else {
var row_total = Number((unitCost * qty) - discount);
}
$(row).find(".dt_subtotal").val(row_total);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="table_invoice">
<row class="dt_row">
Price<input class="form-control form-price dt_unitPrice" name="dt_unitPrice" value="50"></br>
Qty<input class="form-control form-quantity dt_qty" name="dt_qty" value="2"></br>
Discount<input class="form-control form-discount dt_discount" name="dt_discount" value="0"></br>
Total<input class="form-control form-price dt_subtotal" name="dt_subtotal" value="0.00">
</row>
</div>
关于jquery - 如何检查一个值是否包含百分比,然后用百分比对其进行折扣,否则使用其原始值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45054995/