Danny Pearson Danny Pearson - 21 days ago 4x
jQuery Question

Loop parameters not working inside of function jQuery

Everything else within the loop works fine until it gets to the .change function. when I remove the (i + 1) and write the id as minMax1 it works fine so it seems to be something to do with the loop variable. Does anyone know what the problem is?

Outside of the function the console returns 4 different values but inside it returns the same one 4 times.

for (var i = 0; i < 4; i++) {
var wC = weather[i].conditions;
var lowC = data.forecast.simpleforecast.forecastday[i].low.celsius;
var highC = data.forecast.simpleforecast.forecastday[i].high.celsius;
var lowF = data.forecast.simpleforecast.forecastday[i].low.fahrenheit;
var highF = data.forecast.simpleforecast.forecastday[i].high.fahrenheit;
var fDay = data.forecast.simpleforecast.forecastday[i].date.weekday_short;

console.log (wC);

switch (wC) {
case "Clear": case "Sunny":
$("#weatherIcon" + (i + 1)).addClass ("wi wi-day-sunny");
case "Mostly Sunny": case "Mostly Clear": case "Partly Sunny": case "Partly Cloudy":
$("#weatherIcon" + (i + 1)).addClass ("wi wi-day-cloudy");
case "Mostly Cloudy": case "Overcast": case "Scattered Clouds":
$("#weatherIcon" + (i + 1)).addClass ("wi wi-cloudy");

$("#todayTemp").html (todayTempC + "&deg;");
$("#minMax" + (i + 1)).html (lowC + "&deg; / " + highC + "&deg;");

$("input:radio[name=\"system\"]").change (function () {

if ($(this).val() == "cel"){
$("#todayTemp").html (todayTempC + "&deg;");
$("#minMax" + (i + 1)).html (lowC + "&deg; / " + highC + "&deg;");
else if ($(this).val() == "far") {
$("#todayTemp").html (todayTempF + "&deg;");
$("#minMax" + (i + 1)).html (lowF + "&deg; / " + highF + "&deg;");

$("#fDay" + i).html (fDay);



Inside the callback method, i refers to the value of i when the callback is called. This means that i will always be 4 at that time (the callback will always execute after the loop has finished all iterations). You'll need to create a separate context for each iteration to access the value at the current iteration.

Array.forEach will do this automatically for example.

['a', 'b'].forEach(function (value, i) {
    //First iteration: value = 'a', i = 0 
    //Second iteration: value = 'b', i = 1

You can also bind i to your callback method. See this example: