There are 2 problems that I can see.
- You are overriding the contents of postto in the loop instead of appending to it.
- The use of the closure variable
data
in the loop is not correct(See Creating closures in loops: A common mistake & Javascript closure inside loops - simple practical example).
So try
$(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) {
//clear the container
$(postTo).empty('');
while (startNumSections != sectNumToCreate) {
var data = {
section: currentAddSection
};
//use a local closure for the data variable
(function (data) {
$("#templates").load("../SCSectionTemplate #SCSectionTemplate", function () {
var template = document.getElementById('SCSectionTemplate').innerHTML;
var output = Mustache.render(template, data);
//keep appending new items from the loop
$(postTo).append(output);
});
})(data);
currentAddSection = currentAddSection + 1;
startSectNum = startSectNum + 1;
startNumSections = startNumSections + 1;
}
}
});