不显示计算结果

时间:2019-04-06 11:33:02

标签: javascript jquery html

我有一个计算总金额的jquery代码。

$("#quantity").on("change keyup paste", function() {
  var quantity = $(this).val();
  //$('#display').text(quantity);
})

$("#buy").on("change keyup paste", function() {
  var buy = $(this).val();
})

var total_amnt = (((quantity * buy) * 5) / 100) + (quantity * buy);
$('#tot_amnt_display').text(total_amnt);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<table class="table">
  <tbody>
    <tr style="text-align: center;">
      <td>Quantity</td>
      <td>Buy</td>
    </tr>
    <tr>
      <td><input type="number" class="form-control" id="quantity" placeholder="Quantity" name="quantity"></td>
      <td><input type="number" class="form-control" id="buy" placeholder="Buy Amount" name="buy"></td>
    </tr>
  </tbody>
</table>
<table class="table table-bordered table-dark">
  <tbody>
    <tr>
      <td>Total Amount</td>
      <td><span id="tot_amnt_display"></span></td>
    </tr>
  </tbody>
</table>

在上面代码的结果中,它仅显示 NaN

页面加载 在输入框中输入值!

1 个答案:

答案 0 :(得分:1)

该值的默认类型为字符串类型,应将值转换为数字。另外,您不需要多个事件处理程序,只需传递用逗号分隔的ID。

尝试以下方式:

$("#quantity, #buy").on("change keyup paste", function() {
  var quantity = Number($('#quantity').val());
  var buy  = Number($("#buy").val());
  var total_amnt = (((quantity * buy) * 5) / 100) + (quantity * buy);
  $('#tot_amnt_display').text(total_amnt);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<table class="table">
  <tbody>
    <tr style="text-align: center;">
      <td>Quantity</td>
      <td>Buy</td>
    </tr>
    <tr>
      <td><input type="number" class="form-control" id="quantity" placeholder="Quantity" name="quantity"></td>
      <td><input type="number" class="form-control" id="buy" placeholder="Buy Amount" name="buy"></td>
    </tr>
  </tbody>
</table>
<table class="table table-bordered table-dark">
  <tbody>
    <tr>
      <td>Total Amount</td>
      <td><span id="tot_amnt_display"></span></td>
    </tr>
  </tbody>
</table>