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 te
This should fix it:
var total = 0;
$(".price").each( function(){
total += $(this).val() * 1;
});
$(".price").each(function(){
total_price += parseFloat($(this).val());
});
please try like this...
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
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
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()"><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>
$('.price').blur(function () {
var sum = 0;
$('.price').each(function() {
sum += Number($(this).val());
});
// here, you have your sum
});