javascript - 自动填写的计算表格

标签 javascript jquery forms input

我有一个 <select>对于产品,当选择一个选项时 input #price自动填充 data-price ,然后在输入#quantity中输入数量最后输入 #sumprice*quantity 的结果.如何在更改输入和选择时求和?

$('#product').change(function() {
  var price = parseInt($(this).children("option:selected").attr("data-price"));
  $("#price").attr("value", price);
});

$('#quantity').on('input propertychange paste change', function(e) {
  var quantity = $('#quantity').val();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="product">
      <option value="1" data-price="100">Product 1</option>
      <option value="2" data-price="200">Product 2</option>
      <option value="3" data-price="300">Product 3</option>
    </select>
<input type="text" id="price" value="" readonly>
<input type="number" id="quantity" min="1" max="9999999" step="1">
<input type="text" id="sum" readonly="">

最佳答案

添加一个额外的“计算总数”函数,并从两个事件处理程序中调用它。只要其中任何一个发生变化,总数就会更新。

$('#product').change(function() {
  var price = parseInt($(this).children("option:selected").data("price"));
  $("#price").val(price);
  calcTotal();
});

$('#quantity').on('input propertychange paste change', function(e) {
  calcTotal();
});

function calcTotal() {
  var price = $('#price').val() || 0;
  var qty = $('#quantity').val() || 0;
  var total = price * qty;

  $('#sum').val(total);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="product">
  <option value="1" data-price="100">Product 1</option>
  <option value="2" data-price="200">Product 2</option>
  <option value="3" data-price="300">Product 3</option>
</select>
<input type="text" id="price" value="" readonly>
<input type="number" id="quantity" min="1" max="9999999" step="1">
<input type="text" id="sum" readonly="">

关于javascript - 自动填写的计算表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45696934/

相关文章:

c# - Ingenico 6550 不会显示签名框

javascript - react : refactoring multiple form inputs

javascript - 两个字符之间的子字符串

javascript - 将图像转换为内容背景

jquery - 如何使用数据表对包含数字和图像的列进行排序

javascript - jQuery/Javascript > onClick 将文本放置在最后已知的光标位置

javascript - 使用 JavaScript 填充 <select>

javascript - 使用 lodash 解析 URL 字符串

javascript - JQuery:解析 ajax 调用与嵌入的 str

javascript - 水平拖动阻止了页面默认的垂直滚动