Marco Marco - 6 months ago 22
Javascript Question

Jquery - adding number to each iteration starting from 1

I would like to add numbers starting from 1 to each element added in my loop.

This is the code:

function(data, status){
var cleanData = $.parseJSON(data);
var i = 1;
$.each(cleanData, function(key, value, i) {
$( "#list" ).append(
"<div class='large-12 columns'><div class='large-1 columns'>" + (++i) + "</div><div class='large-10 columns'><p> " + value.title + "</p></div><div class='large-1 columns'>" + value.count +"</div></div>" );
});
}


I have also tried it with
(i+1)
but then I get
NaN


So, that the end result would be something like this:

1 title count
2 someOtherTitle count
3 anotherTitle count

Answer

So I'm not entirely sure what is wrong but maybe try removing i from the function parameters as it's within scope anyways. Also use i++(read then increment) or set i = 0. Otherwise you'll be starting at 2.

function(data, status){
   var cleanData = $.parseJSON(data);
   var i = 0;
   $.each(cleanData, function(key, value) {
      $( "#list" ).append(
        "<div class='large-12 columns'><div class='large-1 columns'>" + (++i) + "</div><div class='large-10 columns'><p> " + value.title + "</p></div><div class='large-1 columns'>" + value.count +"</div></div>" );
    });
}