I have a for loop that iterates over dependent fields in a form. The array looks like this:
var dependentFields = [
{ parent: FLDID_LABEL, children: [FLDID_LABEL_TEMPLATE, FLDID_LABEL_INSTRUCTIONS], choiceTrigger: 'Yes', markAsReq: true },
{ parent: FLDID_SHIP_TO, children: [FLDID_SHIP_TO_ADDR], choiceTrigger: 'No', markAsReq: true }
];
I have a function that gets called to attach all the event handlers. For simplicity, I will show just the loop where the problem is occurring.
function attachEventHandlers() {
// begin dependent fields
for (var i = 0; i < dependentFields.length; i++) {
var o = dependentFields[i];
$('#' + o.parent).change(function () {
var visible = $('#' + o.parent + ' :selected').text() === o.choiceTrigger;
for (var c = 0; c < o.children.length; c++) {
var child = o.children[c];
showField(child, visible);
if (o.markAsReq && $('#' + child).val() === '') {
MarkFieldAsRequired(child);
}
}
});
}
}
Only the second dependent field works and the first one does not. I think this is related to the way var i
or var o
is referenced from the outer function. Effectively the same event handler gets attached to all the dependent fields. How can I fix this?
EDIT: Here is a jsfiddle with the bug: http://jsfiddle.net/H3Bv2/4/ Notice how changing either of the parents only affects the second child.