0

I'm trying to set click actions on some generated jQuery buttons. But in my code I think is something wrong because if I click on any of the buttons console.log(buttonid) will display #btn170, which means the last button(data.incidentList.length). What is curious, the following line $(buttonid).css( "border", "3px solid red" ) seems to work ok, all the buttons are red borders.

for(var j=0; j<=data.incidentList.length; j=(parseInt(j)+parseInt(itemInterval))) {
    var buttonid = '#btn'+ parseInt(j+1);
    $(buttonid).css( "border", "3px solid red" ); 

    $(buttonid).click(function () {
        console.log(buttonid);
    });
}
eu127
  • 123
  • 1
  • 14
  • you dont need `parseInt` when you already have a number! (not the reason why your code doesnt do what you expect) – Jamiec Oct 29 '15 at 11:32

1 Answers1

1

You need to wrap the code for the button click in a closure, otherwise by the time you click any button it has already incremented your j variable up to its limit.

for(var j=0; j<=data.incidentList.length; j+= itemInterval)) {
    var buttonid = '#btn'+ (j+1);
    $(buttonid).css( "border", "3px solid red" ); 
    (function(b){
        $(b).click(function () {
            console.log(b);
        });
    })(buttonid);
}

Note: Ive also got rid of the unnecessary parseInt calls.

Finally, some further reading for you

Community
  • 1
  • 1
Jamiec
  • 133,658
  • 13
  • 134
  • 193