Given: I have elements with values of integers floats (thank you, Pointy) up to two decimal places (such as: 1.50 and 2.25).
Goal: Collect the values of several elements and add them together. (such as: 1.50 + 2.25 = 3.75 )
Code:
$(".quantity").keyup(function(){
var sum = 0.00;
var subTotals = document.getElementsByClassName("sub-total")
$.each(subTotals, function(){
sum += $(this).val() << 0
});
$("#products_revenue_income").val(sum)
});
Issue: I'm used to Ruby, so I presumed that iterating over an array of [1.5, 2.25] you could add the elements together with +=
, to get 3.75
, but my return value was 01.502.25
, appearing to (1) add a zero to the left and (2) treat the values as a string. When I added the shift operator <<
, it removed the left zero and treated the values like integers again, but it rounded the total, so my return value is 3
.
What I've tried: I've tried using parseFloat($(this).val()).toFixed(2)
within the block to make sure each value is treated as an integer but it doesn't appear to have any effect on the result.
Tech: jQuery version: 1.7.1.
Thank you for your time Let me know if you require any additional context.
This is happening because jQuery's val()
method returns the value
property of the matched element which is a string type. This means you're falling into the string concatenation trap ("1"
+ "1"
= "11"
). You can convert your value into a number using a Unary plus (+
):
sum += +$(this).val();
Also worth noting that value
is a native property of this
, so you can drop the jQuery wrapper and method here altogether:
sum += +this.value;