0

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);
}
Dale
  • 1,289
  • 3
  • 16
  • 36

1 Answers1

1

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.

Community
  • 1
  • 1
Buzinas
  • 11,597
  • 2
  • 36
  • 58
  • Works great! Thank you. And that link was very helpful and informative as well. Although, I'm still now sure how to use that info for a better solution to this particular problem but I'm still thinking about it and have few ideas to try. – Dale Sep 15 '15 at 19:41