1

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.

2 Answers 2

2

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>
Sign up to request clarification or add additional context in comments.

3 Comments

Based on what the OP wants, I would recommend declaring sum inside the success callback (the line just before $.each).
Agreed. That makes sense. +1
@DinoMyte Thanks for answering! I haven't programmed with jQuery for awhile, I didn't know it could be that simple!
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.