Reputation: 1301
I'm trying to add an onclick event handler to a list of checkboxes. Instead of alerting the checkbox ID that I would expect it to (the one I'm clicking on), it's always alerting checkbox number 3 regardless of which on I click. Why is this and how can I get this to behave as desired. When I click on checkbox 2, I want it to alert "2"... etc.
function component (componentId, displayType, parentId) {
this.componentId = componentId;
this.parentId = parentId;
this.displayType = displayType;
}
var components = [];
components.push(new component(0, null, null);
components.push(new component(1, null, null);
components.push(new component(2, null, null);
components.push(new component(3, null, null);
var arrayLength = components.length;
for (var i = 0; i < arrayLength; i++) {
var component = components[i];
jQuery('#questionnaireComponentId'+component.componentId).find('input:checkbox').click(
function(){
selectParentCheckbox(component.componentId);
}
);
}
function selectParentCheckbox(componentId){
alert(componentId);
}
Upvotes: 0
Views: 17
Reputation: 11733
This is happening because of the Javascript closures.
You should pass the parameter each iteration, and not only after finishing the iteration.
for (var i = 0; i < arrayLength; i++) {
var component = components[i];
jQuery('#questionnaireComponentId' + component.componentId)
.find('input:checkbox')
.click(selectParentCheckbox.bind(null, component.componentId));
}
The bind
function allows you to name what the function the click event will be calling and what parameters should be passed to it.
Nothing to do with the question, but only for your information: I think you're misunderstanding the power of jQuery and its event delegation, since you could use a much better aproach at all.
Upvotes: 1