I have the following HTML.
<div id="price_list">
<input type="text" value="100" class="input_price" />
<input type="text" value="256" class="input_price" />
<input type="text" value="500" class="input_price" />
<input type="text" value="04.26" class="input_price" />
<input type="text" value="156" class="input_price" />
<input type="text" value="052" class="input_price" />
<input type="text" value="692" class="input_price" />
<input type="text" value="25.36" class="input_price" />
<input type="text" value="10.56" class="input_price" />
</div>
What is the best way to get the SUM of values of the elements having class input_price?
Please note that I am concerned about the performance. My actual HTML is bit more complex (sometimes I have thousands of elements). I tried using .each() but sometimes my browser gets stuck. So that the question can be modified to "What is the best way to iterate through elements TO GET some data?"
My try:
var total = 0;
$(".input_price").each(function(){
total+=parseFloat($(this).val());
});
Just because you care about performance, use pure JavaScript and a single for loop:
var list = document.getElementById("price_list"),
inputs = list.getElementsByTagName("input"),
total = 0;
for (var i = 0, len = inputs.length; i < len; i++) {
total += +inputs[i].value;
}
console.log(total);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With