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);
}
1
  • can you share your generated html as well? Commented Sep 15, 2015 at 19:18

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.