Reputation: 1
I am new to java script and having a problem.
I am creating a form dynamically from Json string what we obtain some how ( not relevant ) - Keeping all those controls information in Array (allParamArray in code) . A control can have parent , hence a parent control can have dependents ( children ) - I want to attach onchange event to each control which have dependents . The dependents are comma separated and taken care of in the refreshDependents function.
<code>
for (mp = 0; mp < allParamsArray.length; mp++) {
if (allParamsArray[mp].dependents) {
var parent = allParamsArray[mp].name;
var dependents = allParamsArray[mp].dependents;
document.getElementById(parent).onchange = function() {
refreshDependents(parent, dependents, this.selectedIndex)
};
}
}
</code>
The Problem is , when I change value on form for a control refreshDependents has the last parent information and not of the control which I change.
I was wondering is there any way we can achieve multiple control pointing to same onchange function and in onchange function
we get the correct information about the control which is being changed ?
Upvotes: 0
Views: 501
Reputation: 20254
This should do it:
function makeHandler(parent, dependents, selectedIndex){
return function(){
refreshDependents(parent, dependents, selectedIndex);
};
}
for (mp = 0; mp < allParamsArray.length; mp++) {
if (allParamsArray[mp].dependents) {
var parent = allParamsArray[mp].name;
var dependents = allParamsArray[mp].dependents;
document.getElementById(parent).onchange = makeHandler(parent, dependents, this.selectedIndex);
}
}
The makeHandler
function returns a new function object, which will keep the values that the parent
, dependents
, and selectedIndex
variables had at the time it was created.
Upvotes: 0