vlovystack
vlovystack

Reputation: 703

Generate .click functions inside for loop

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..

Upvotes: 1

Views: 42

Answers (2)

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48367

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++) {
     ^^^

Upvotes: 1

Marius Turcu
Marius Turcu

Reputation: 1511

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));

Upvotes: 0

Related Questions