我如何自动(通过每个函数)对字段求和以总结一些输入字段,如下所示:
<input name="price_1" id="price_1" type="text" value="50" />
<input name="price_2" id="price_2" type="text" value="40" />
<input name="price_3" id="price_3" type="text" value="20" />
<input name="price_4" id="price_4" type="text" value="10" />
<input name="price_5" id="price_5" type="text" value="80" />
非常感谢有人提出建议吗?
答案 0 :(得分:1)
使用jQuery;
<script src="{path to jquery}/resources/js/vendor/jquery-1.9.0.min.js"></script>
<script>
$(document).ready(function() {
var total = 0;
$.each($('input'), function(){
total += parseInt($(this).val(), 10); //use radix 10 to ensure correct parseInt val
});
console.log(total);
});
</script>
答案 1 :(得分:0)
<input name="price_1" id="price_1" type="text" value="50" />
<input name="price_2" id="price_2" type="text" value="40" />
<input name="price_3" id="price_3" type="text" value="20" />
<input name="price_4" id="price_4" type="text" value="10" />
<input name="price_5" id="price_5" type="text" value="80" />
var inputs = document.getElementsByTagName("input");
function sumIt() {
var sum = Array.prototype.reduce.call(inputs, function (a, b) {
return a + parseFloat(b.value);
}, 0);
console.log(sum);
}
Array.prototype.forEach.call(inputs, function (input) {
input.addEventListener("keyup", sumIt, false);
});