javascript - 使用数据属性计算输入字段

标签 javascript jquery html forms web

我有带数据属性的输入字段。我希望在字段总计中单击按钮时是所有字段总计的总和。我找到了每个字段的总和,但是如何对所有字段求和。

<input type="text" id="total">
<div class="field">
  <input type="number" min="1" max="255" data-price="2" class="wert">
</div>
<div class="field">
  <input type="number" min="1" max="255" data-price="2" class="wert">
</div>
<button id="calc-butt">Sum</button>
<script>
 jQuery('#calc-butt').click(function() {
    jQuery('.field').each(function(){
      var price = jQuery(this).find('.wert').attr("data-price");
      var cubic = jQuery(this).find('.wert').val();
      var total = price * cubic;

    });
 });
</script>

最佳答案

total 的范围只在 each 回调中,在 each 之前将其初始化为 0,检查代码片段

jQuery('#calc-butt').click(function() {
    var total = 0;
    jQuery('.field').each(function(){
      var price = jQuery(this).find('.wert').attr("data-price");
      var cubic = jQuery(this).find('.wert').val();
      total += price * cubic;
      jQuery('#total').val(total);
    });
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="total">
<div class="field">
  <input type="number" min="1" max="255" data-price="2" class="wert">
</div>
<div class="field">
  <input type="number" min="1" max="255" data-price="2" class="wert">
</div>
<button id="calc-butt">Sum</button>

关于javascript - 使用数据属性计算输入字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46205029/

相关文章:

javascript - 在 typescript 主体前后插入缩进?

javascript - 如何在 jquery 中使用 post 进行 for 循环

php - jQuery UI TABS + AJAX + PHP 动态内容加载

jquery - 混合多个 jQuery 文件 - 最佳实践?

html - 不同分辨率下的CSS全屏问题

javascript - JQM 1.4.0 上的自定义转换设置出现 "has no method ' 转换 '"错误?

javascript - 为什么 typeof array[0] == 'undefined' 不起作用?

javascript - 在带有参数的 javascript 中调用 php 函数

javascript - 当变量值有空格时如何在kendo UI的itemTemplate中渲染JS变量

html - bootstrap 表单内部不需要 bootstrap btn-group?