I'm having a problem looping with a .load function inside the loop. I'm passing in a value from a listbox wich indicates the amount of sections to create. I'm using Moustache to load the template from a seperate file. This should create the amount of sections in the listbox but all I end up with is the last section created and none of the others. Following the code through the debugger the .load function doesn't want to fire until the last pass of the loop. The listbox on.(change) is as follows:
$(document).on('change', '#SCTotSections', function () {
var sectNumToCreate = parseInt($('#SCTotSections :selected').val(), 10);
var startNumSections = parseInt(startSectNum, 10);
var currentAddSection = startNumSections + 1;
var postTo = '#writeToTest';
if (sectNumToCreate < startNumSections)
{
if (startNumSections != sectNumToCreate )
{
var myNode = document.getElementById("S" + startNumSections)
myNode.remove();
//while (myNode.firstChild) {
// myNode.removeChild(myNode.firstChild);
//}
startSectNum = startSectNum - 1;
startNumSections = startNumSections - 1;
}
}
else if (sectNumToCreate > startNumSections)
{
while (startNumSections != sectNumToCreate)
{
var data = {
section: currentAddSection
};
$("#templates").load("../SCSectionTemplate #SCSectionTemplate", function () {
var template = document.getElementById('SCSectionTemplate').innerHTML;
var output = Mustache.render(template, data);
$(postTo).html(output);
});
currentAddSection = currentAddSection + 1;
startSectNum = startSectNum + 1;
startNumSections = startNumSections + 1;
}
}
});