Mae
Mae

Reputation: 433

Making a counting sum in jQuery each

How can I count in a jQuery each function?

<script>
    ajax();
    function ajax(){
        $.ajax({
            url:"ChinaWeather.json",
            dataType:"json",
            success: function(data){
                $.each(data, function(index, item){ 
                    var sum = 1;
                    $('#countryweatherwrap').append('<div id="countryweather' + sum + '">' + data[index].season + 'Temperatuur: ' +
                        data[index].temperature+' °C <br />' + '<div style="height:'+ data[index].temperature*5.50  +'px;width:100%;border:1px solid #000; background-color:yellow"></div></div>'
                        );  
                    });
            }
        })
    }   
</script>

At the moment the code returns <div id="countryweather"> in every loop. I want it to count so it returns <div id="countryweather2">, <div id="countryweather3"> etc.

Upvotes: 1

Views: 227

Answers (2)

DinoMyte
DinoMyte

Reputation: 8868

a. Move var sum outside the each loop ( make it global )
b. Increment the value of sum by 1 via ++;

<script>        
    ajax();
    function ajax(){        
        $.ajax({
            url:"ChinaWeather.json",
            dataType:"json",
            success: function(data){
                var sum = 1;
                $.each(data, function(index, item){                    
                    $('#countryweatherwrap').append('<div id="countryweather' + sum + '">' + data[index].season + 'Temperatuur: ' +
                        data[index].temperature+' °C <br />' + '<div style="height:'+ data[index].temperature*5.50  +'px;width:100%;border:1px solid #000; background-color:yellow"></div></div>'                      
                        );  
                      sum++;
                    });
            }
        })
    }   
</script>

Upvotes: 2

putvande
putvande

Reputation: 15213

You can use the index:

$.each(data, function(index, item) {
    $('#countryweatherwrap').append('<div id="countryweather' + (index+1) + '">' + data[index].season + 'Temperatuur: ' + data[index].temperature + ' °C <br />' + '<div style="height:' + data[index].temperature * 5.50 + 'px;width:100%;border:1px solid #000; background-color:yellow"></div></div>');
});

That has an index starting at 0 so add 1.

Upvotes: 1

Related Questions