javascript - 如何使用 javascript/jquery 在 span 中写入所有输入类型值的总和?

标签 javascript jquery html html-input

目前,我可以输出它们的每个值并将其显示为一个系列,但我想要的是对它们的所有值求和并显示其总数。

这是我的示例代码:

Javascript

$(function() {
  $('input[name=selectProducts]').on('change', function() {    
    $('#products').text($('input[name=selectProducts]:checked, input[name=selectProducts][type=text]'').map(function() {
      return this.value;
    }).get());
  });
});

HTML

<input type="checkbox" name="selectProducts" id="product1" value="5" />
<input type="checkbox" name="selectProducts" id="product2" value="5" />
<input type="checkbox" name="selectProducts" id="product3" value="5" />
<!-- i want to include these input type text -->
<input type="text" name="selectProducts" id="product4" value="10" />
<input type="text" name="selectProducts" id="product5" value="10" />
<span name="products" id="products"></span>

输出

5,5,5,10,10


35  <!-- my desired output should look like this -->

我想把它们加起来得到 35 的总数。 请帮助我。

最佳答案

使用 .toArray()将 jquery 对象转换为数组并使用 .reduce()遍历数组项和求和值。

$('input[name=selectProducts]').on('change', function() {    
    $('#products').text(function(){
        return $('input[name=selectProducts]:checked, input[name=selectProducts][type=text]').toArray().reduce(function(tot, val) {
            return tot + parseInt(val.value);
        }, 0);
    });
});

$('input[name=selectProducts]').on('change keyup', function() {    
  $('#products').text(function(){
    return $('input[name=selectProducts]:checked, input[name=selectProducts][type=text]').toArray().reduce(function(total, val) {
      return total + parseInt(val.value);
    }, 0);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="selectProducts" id="product1" value="5" />
<input type="checkbox" name="selectProducts" id="product2" value="5" />
<input type="checkbox" name="selectProducts" id="product3" value="5" />
<input type="text" name="selectProducts" id="product4" value="10" />
<input type="text" name="selectProducts" id="product5" value="10" />
<span name="products" id="products"></span>

关于javascript - 如何使用 javascript/jquery 在 span 中写入所有输入类型值的总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52531497/

相关文章:

javascript - Bootstrap Nav Pills Steps ...如何使浏览器在点击时跳转到页面顶部?

javascript - Highcharts 工具提示断线

html - 个人资料照片上的按钮

javascript - drag 和 dragstart 事件类型之间的确切区别(?)

javascript - CSS 背景图像未显示在 Android 设备中

Javascript 到 Java Applet 未捕获类型错误 : Object #<HTMLAppletElement> has no method

javascript - anchor 标记在 jquery slider 中不起作用

jquery - 在 Jquery 中制作函数

html - 将背景图像宽度缩放到 div 的大小

javascript - 如何获得小时: "2-digit" for toLocaleString ("en-US") with AM/PM?的正确输出