milano
milano

Reputation: 475

How to add up the result in $.each loop?

Hi i am trying to read width of each item in topmenu element and add the width of item and assign to avariable. but when i run this code i am getting NaN in alert what is the problem in this code:

$(document).ready(function(){
    $('.topmenu').each(function(menu){
        var btext = $(this).find('.baritem').width();
        alert(btext);
        var itemswidth = +itemswidth+btext;
        alert(itemswidth);
        //var width = getTextWidth(btext,"arial","40");
        //alert(width);     
    });
});

Upvotes: 3

Views: 95

Answers (2)

Denys Séguret
Denys Séguret

Reputation: 382150

This line

var itemswidth = +itemswidth+btext;

adds undefined to a number. This gives NaN. You need to initialize itemswidth to 0 before entering the loop :

$(document).ready(function(){
  var itemswidth = 0;
  $('.topmenu').each(function(){
     var btext = $(this).find('.baritem').width();
     itemswidth += btext;
     console.log(itemswidth); // better than alert
  });
});

And for Florian :

$(document).ready(function(){
    var itemswidth = $('.topmenu .baritem').get().reduce(function(t,e){ 
        return t+$(e).width()
    }, 0);
    console.log(itemswidth);
});

Upvotes: 11

Thomas Junk
Thomas Junk

Reputation: 5676

You could do it easily with:

var reduce=Array.prototype.reduce;
var completeWidth=reduce.call($("div"), function(sum, elem){
    sum+=$(elem).width();
    return sum;
}, 0);

http://jsfiddle.net/DSUHG/

Upvotes: 0

Related Questions