1

Inside my for loop that loops through 15 "box" objects, code below:

for (var i = 0; i < boxesLength; i++) {

I'm trying to generate these click events automatically, they used to be like this: (all the way up until 15)

$("#box0").click(function(){
    var rw = 462;
    var input = $('#rw');
    input.val(rw);

    var rh = 310;
    var input = $('#rh');
    input.val(rh);
    calculateRectangle();
    calculateRectangle2();
});

Right now I am trying to auto-generate these in the for loop by doing this:

$("#box" + i).click(function(){
    var rw = allBoxes[i].width;
    var input = $('#rw');
    input.val(rw);

    var rh = allBoxes[i].length;
    var input = $('#rh');
    input.val(rh);
    calculateRectangle();
    calculateRectangle2();
});

What am I doing wrong? When I console log "#box" + i I am getting the expected result..

1
  • Why are you setting 15 different event listeners to the boxes, instead of setting just 1 to a common ancestor and delegating it to them? Your code becomes extremely repetitive that way. Commented Oct 4, 2018 at 7:37

2 Answers 2

1

This is an exemple of closures. When you're trying to click one button then your alghorithm will use the last value of i variable which is boxesLength.

To solve this, just use letkeyword.

for (let i = 0; i < boxesLength; i++) {
     ^^^
Sign up to request clarification or add additional context in comments.

Comments

0

Another solution will be like this:

$("#box" + i).click(function(i){
return function(){
    var rw = allBoxes[i].width;
    var input = $('#rw');
    input.val(rw);

    var rh = allBoxes[i].length;
    var input = $('#rh');
    input.val(rh);
    calculateRectangle();
    calculateRectangle2();
}}(i));

Comments

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.