Red
Red

Reputation: 6378

jQuery iterate through elements

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());    
});

Upvotes: 3

Views: 8457

Answers (5)

Optimus Prime
Optimus Prime

Reputation: 6907

Summing all elements with classes as input_price,

var elements = document.getElementsByClassName("input_price");
var sum = 0;
for(var i=0; i<elements.length; i++) {
    sum += parseFloat(elements[i].value);
}

Upvotes: 0

Joseph
Joseph

Reputation: 119837

In jQuery, you could do this straight:

var sum = 0;

$('.input_price').each(function(){
  var value = parseFloat(this.value);
  if(!isNaN(value)) sum += value;
});

You could also do asynchronous looping using timers. It will take longer but will not freeze the UI thread so you won't get stuck. Here's a demo where it sums up an array of 1's until 1000, but won't freeze the browser.

function loop(object,callback){
  var i = 0;
  var sum = 0;

  var timer = setInterval(function(){

    //get value and add
    var value = parseFloat(object[i].value);
    if(!isNaN(value)) sum += value;

    //if we reach the length, clear the timer and call the callback
    if(++i === object.length){
      clearInterval(timer);
      callback(sum);
    }
  },0);
}

loop($('.input_price'),function(sum){
  console.log(sum);
});

Upvotes: 3

PSR
PSR

Reputation: 40318

$('.input_price').each(function(){
    sum += parseFloat($(this).val());
});

Upvotes: 0

VisioN
VisioN

Reputation: 145378

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);

Upvotes: 5

Yatrix
Yatrix

Reputation: 13775

var sum = 0;

$('.input_price').each(function(){
    sum += parseFloat(this.value);
});

Upvotes: 1

Related Questions