jquery - 如何检查一个值是否包含百分比,然后用百分比对其进行折扣,否则使用其原始值?

标签 jquery

我正在做一个折扣功能,用户可以输入折扣金额,例如如果用户输入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/

相关文章:

Javascript 与 JSON 请求同步

javascript - jQuery .slideToggle() 重复

javascript - FadeInUp css 动画不工作

javascript - angular.js 从数组中获取特定值

jquery - "if height is larger than X"不工作

jquery - 在网站中下载的图像的图像进度条在 FF 中无法使用适当的结果

javascript - Kendo Grid 更新时表现奇怪

jquery - 如何在 VS.NET 2012 中的 ASP.NET Web 表单中使用 jQuery 文件?

javascript - 仅在第一层对带有嵌套列表的未排序列表 (li) 进行排序

Javascript 元素 id 到 AJAX url