Your first problem is that you redefine i
as parameter for your function, which overwrites the i
from your for-loop. By removing that parameter you now can reference that inside the function:
for (var i = 0; i < ToggleCount; i++) {
ToggleFolder[i] = gui.addFolder(ToggleDescription[i]);
ToggleChange[i] = { Status: false, Auto: false };
ToggleStatus[i] = ToggleFolder[i].add(ToggleChange[i], 'Status', false).listen();
ToggleAuto[i] = ToggleFolder[i].add(ToggleChange[i], 'Auto', false).listen();
ToggleStatus[i].onFinishChange(function (value) {
console.log(i);
$.ajax({
url: 'StatusUpdate.php',
type: 'get',
data: 'ToggleDevice=' + ToggleDescription[i] + '&val=' + value,
success: function (result) { }
});
console.log(ToggleDescription[i]);
});
ToggleFolder[i].open();
}
Now you will run into another problem though: when the onFinishChange function is called, the i
variable will have changed already (probably it will be equal to the length of the array), so your index will be wrong. To fix that, you have to create an immediate function to capture the value:
for (var i = 0; i < ToggleCount; i++) {
ToggleFolder[i] = gui.addFolder(ToggleDescription[i]);
ToggleChange[i] = { Status: false, Auto: false };
ToggleStatus[i] = ToggleFolder[i].add(ToggleChange[i], 'Status', false).listen();
ToggleAuto[i] = ToggleFolder[i].add(ToggleChange[i], 'Auto', false).listen();
ToggleStatus[i].onFinishChange((function(index){
return function (value) {
console.log(index);
$.ajax({
url: 'StatusUpdate.php',
type: 'get',
data: 'ToggleDevice=' + ToggleDescription[i] + '&val=' + value,
success: function (result) { }
});
console.log(ToggleDescription[index]);
})
})(i));
ToggleFolder[i].open();
}