我有一个包含大约30个包含数字值的文本字段的订单。我想计算所有这些值的总和。
我知道如何选择所有文本字段,但不知道如何遍历它们并求和所有值?
$(document).ready(function(){
$(".price").blur(function() {
//loop and add up every value from $(".price").val()
})
});
我有一个包含大约30个包含数字值的文本字段的订单。我想计算所有这些值的总和。
我知道如何选择所有文本字段,但不知道如何遍历它们并求和所有值?
$(document).ready(function(){
$(".price").blur(function() {
//loop and add up every value from $(".price").val()
})
});
Answers:
$('.price').blur(function () {
var sum = 0;
$('.price').each(function() {
sum += Number($(this).val());
});
// here, you have your sum
});
为您的项目提供更通用的复制/粘贴功能。
sumjq = function(selector) {
var sum = 0;
$(selector).each(function() {
sum += Number($(this).text());
});
return sum;
}
console.log(sumjq('.price'));
.val(),而不是.text()
如果不需要支持IE8,则可以使用本机JavascriptArray.prototype.reduce()方法。您首先需要将JQuery对象转换为数组:
var sum = $('.price').toArray().reduce(function(sum,element) {
if(isNaN(sum)) sum = 0;
return sum + Number(element.value);
}, 0);
参考:https : //developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
使用此功能:
$(".price").each(function(){
total_price += parseInt($(this).val());
});
parseFloat()
这应该解决它:
var total = 0;
$(".price").each( function(){
total += $(this).val() * 1;
});
var total = 0; $(".price").each( function(){ total += $(this).val() * 1; });
$(".price").each(function(){
total_price += parseFloat($(this).val());
});
请尝试这样...
"2 apples" + "3 oranges" => 5
这将100%起作用:
<script type="text/javascript">
function calculate(){
var result = document.getElementById('result');
var el, i = 0, total = 0;
while(el = document.getElementById('v'+(i++)) ) {
el.value = el.value.replace(/\\D/,"");
total = total + Number(el.value);
}
result.value = total;
if(document.getElementById('v0').value =="" && document.getElementById('v1').value =="" && document.getElementById('v2').value =="" ){
result.value ="";
}
}
</script>
Some number:<input type="text" id ="v0" onkeyup="calculate()"><br>
Some number:<input type="text" id ="v1" onkeyup="calculate()"><br>
Some number:<input type="text" id ="v2" onkeyup="calculate()"><br>
Result: <input type="text" id="result" onkeyup="calculate()" readonly><br>