1

I am a newbie to JavaScript, and I am having a JavaScriptwhich creates 8 image buttons to a HTML page. I want to insert a function in each generated imagebutton which could return a particular id, but the issue is when I click any button I am getting only id:8. But I want id:1 for first button and so on. data= {id:1,id:2.....id:8} and some image

for(var i=0;i<8;i++){
    var x=data[i].image;    //this is the image I gets from a JSON string
    var y=data[i].name;     //this is the name I gets from a JSON string
    var id=data[i].id;      //this is the id I gets from a JSON string
    var body = document.getElementsByTagName("body")[0];
    var myButton = document.createElement("input");  
    myButton.src=x;
    myButton.name=String(id);
    myButton.id=data[i].id;
    myButton.type = "image";
    body.appendChild(myButton);

    //i need help with below section
    myButton.onclick = function(){
        console.log("this is my id ",myButton.id);
        //this function will return only the`data[8].id every time  
    };
    console.log(x);
    console.log(y);
    console.log(id);
}
Termininja
  • 6,620
  • 12
  • 48
  • 49
Abdul Rahim A
  • 23
  • 2
  • 6
  • 4
    Possible duplicate of [JavaScript closure inside loops – simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Teemu Jan 13 '17 at 22:12
  • 1
    Yes, it's a closure issue. In all the click listeners, *myButton* references the last button. Use `this.id` instead. – RobG Jan 13 '17 at 22:12

1 Answers1

0

This has a really easy fix.

In your 'onclick' function, don't refer to the button by it's variable name. Replace the variable name "myButton" with 'this':

myButton.onclick = function(){
    console.log("this is my id ",this.id);
    //this function will return only the`data[8].id every time  
};

EDIT:I saw I wasn't the first one to solve your issue. @RobG did it in the comments before me So technically I shouldn't get any credit for this answer.

sj.meyer
  • 835
  • 8
  • 15