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