-1

This is my code:

$(document).on("click", "#farm_0", function(){
  console.log($("#farm_0").attr("my_id"));
  });
$(document).on("click", "#farm_1", function(){
  console.log($("#farm_1").attr("my_id"));
  });

Console shows good values. But when i try use this:

for(var i=0; i < 2; i++)
 {
    $(document).on("click", "#farm_"+i+"", function(){
        console.log($("#farm_"+i+"").attr("my_id"));
     });
}

Button's will work, but console shows just the last value or undefinded. What's wrong with that?

Warmix
  • 217
  • 8
  • 15

1 Answers1

1

You forgot the underscore after #farm in: $(document).on("click", "#farm"+i+"", function(){

FYI: In my opinion you shouldn't use a for loop here.

Try to add a class name to all your elements which you want to be clickable. Then add just 1 event listener for that element and use $(this) inside the event listener to target the clicked button. Like this:

$(document).on("click", ".farm", function(){
    console.log($(this).attr("my_id"));
});

or

$(".farm").on("click", function(){
    console.log($(this).attr("my_id"));
});
Niek Nijland
  • 732
  • 1
  • 7
  • 20
  • ohh thanks! when i wrote this on forum i forgot this underscore, but im my code this underscore exists, but $(this) worked. thanks a lot! – Warmix Mar 15 '17 at 15:39
  • Maybe because of the extra `"` in `console.log($("#farm_"+i+"").attr("my_id"));`. `+""` isn't necessary. – Niek Nijland Mar 15 '17 at 15:42
  • Nice, no problem :) Please accept my answer if you think it answered your question :) – Niek Nijland Mar 15 '17 at 15:43