如何使用javascript/jquery在变化范围内编写所有输入类型值的总和? [英] How to write sum of all input types values in span on change using javascript/jquery?
本文介绍了如何使用javascript/jquery在变化范围内编写所有输入类型值的总和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当前,我可以输出它们的每个值并将其显示为一个序列,但是我想要的是将它们的所有值相加并显示其总计.
Currently, i can output each of their value and display it as a series, but what i want is to sum all of their values and display its total.
这是我的示例代码:
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
的总数.
请帮助我.
I want to sum all of them to get the total of 35
.
Please help me.
推荐答案
使用 .toArray()
将jquery对象转换为数组并使用
Use .toArray()
to converting jquery object to array and use .reduce()
to loop through array items and sum values.
$('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/jquery在变化范围内编写所有输入类型值的总和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文