I have a for loop, which iterates through objects found in JSON, to populate form fields.
With each object it finds, it will .trigger('click') the button which adds the required fields, ensuring there are the correct amount for the user to fill in.
The button that is triggered has a .click() function which appends a section to the form for each object found in the JSON, and the end of that function triggers a custom event, passing in the index of the JSON object .trigger('delegateAdded', delegateIndex).
Finally, my event handler should console.log out each section added, using the index value we passed through earlier.
Expected result (with 3 objects in the JSON in this example):
- for loop iterates over 3 objects, clicks button 3 times.
- 3 form sections are appended to the form.
'delegateAdded'custom event is triggered 3 times, console logging the indexes: 0, 1 & 2
Observed result (with 3 objects in the JSON in this example):
- for loop iterates over 3 objects, clicks button 3 times.
- 3 form sections are appended to the form.
'delegateAdded'custom event is triggered 1 time, console logging the final of the 3 indexes: 2
Here's my code for reference:
var addDelegate = $('#add-delegate');
var delegateContainer = $('#additional-delegates');
var delegateHTML = $('#delegate-container');
var delegateNumber = 1;
var delegateIndex = -1;
var delegateData = $.parseJSON($('#delegateData').html());
var numberOfDeligates = delegateData.length;
// CLICK FUNCTION ON BUTTON
addDelegate.click(function (e) {
e.preventDefault();
delegateNumber++;
delegateIndex++;
var delegateClone = delegateHTML.html();
var delegateNewHTML = delegateClone.replace(/_delegateNumber_/g, delegateNumber).replace(/_delegateIndex_/g, delegateIndex);
delegateContainer.append(delegateNewHTML);
// TRIGGER CUSTOM EVENT
$(document).trigger('delegateAdded', delegateIndex);
});
// ITERATE OVER NUMBER OF JSON OBJECTS
for (var i = 0, iDelegateNum = 2; i < numberOfDeligates;) {
// TRIGGER BUTTON CLICK FOR EACH ITERATION
addDelegate.trigger('click');
// HANDLE CUSTOM EVENT FOR EACH ITERATION
$(document).on('delegateAdded', function (event, dIndex) {
console.log(dIndex);
});
}
As it's only ever the final index that gets logged out, it's like the event gets overwritten with the newest one, but I don't think that's a thing, or is it?