目前,我可以输出它们的每个值并将其显示为一个系列,但我想要的是对它们的所有值求和并显示其总数。
这是我的示例代码:
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/