Reputation: 27779
I have an order form with about 30 text fields that contain numerical values. I'd like to calculate the sum of all those values on blur.
I know how to select all text fields but not how to loop through them and add up all their values?
$(document).ready(function(){
$(".price").blur(function() {
//loop and add up every value from $(".price").val()
})
});
Upvotes: 85
Views: 291334
Reputation: 1
This will work 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()">
Some number:<input type="text" id ="v1" onkeyup="calculate()">
Some number:<input type="text" id ="v2" onkeyup="calculate()">
Result: <input type="text" id="result" onkeyup="calculate()" readonly>
Upvotes: 0
Reputation: 2941
If you don't need to support IE8 then you can use the native Javascript Array.prototype.reduce()
method. You will need to convert your JQuery object into an array first:
var sum = $('.price').toArray().reduce(function(sum,element) {
if(isNaN(sum)) sum = 0;
return sum + Number(element.value);
}, 0);
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
Upvotes: 15
Reputation: 18600
$('.price').blur(function () {
var sum = 0;
$('.price').each(function() {
if($(this).val()!="")
{
sum += parseFloat($(this).val());
}
});
alert(sum);
});
Upvotes: 0
Reputation: 6004
Similarly along the lines of these answers written as a plugin:
$.fn.sum = function () {
var sum = 0;
this.each(function () {
sum += 1*($(this).val());
});
return sum;
};
For the record 1 * x is faster than Number(x) in Chrome
Upvotes: 6
Reputation: 12818
A tad more generic copy/paste function for your project.
sumjq = function(selector) {
var sum = 0;
$(selector).each(function() {
sum += Number($(this).text());
});
return sum;
}
console.log(sumjq('.price'));
Upvotes: 30
Reputation: 31
This should fix it:
var total = 0;
$(".price").each( function(){
total += $(this).val() * 1;
});
Upvotes: 2
Reputation: 4841
Use this function:
$(".price").each(function(){
total_price += parseInt($(this).val());
});
Upvotes: 4
Reputation: 165
$(".price").each(function(){
total_price += parseFloat($(this).val());
});
please try like this...
Upvotes: -1
Reputation: 9888
$('.price').blur(function () {
var sum = 0;
$('.price').each(function() {
sum += Number($(this).val());
});
// here, you have your sum
});
Upvotes: 233