Brett Davis
Brett Davis

Reputation: 162

Populate a table with an array using javascript

I have an html table and I have an array in JavaScript. I'm able to populate the table correctly. The only issue is, I'm adding divs inside the td with an onclick event.

var workout = wo["workout"];

for(i=0;i<workout.length;i++){
    for(j=0;j<workout[i].length;j++){
        for(k=0;k<workout[i][j].length;k++){

            var td = document.getElementById(i+"-"+j);

            var closediv = document.createElement("div");
            closediv.className = "closediv";
            closediv.innerHTML = "x";

            closediv.onclick = function () {
                console.log(workout[i][j][k].id);
            };

            var exdiv = document.createElement("div");
            exdiv.id = workout[i][j][k].id;
            exdiv.className = workout[i][j][k].extype;
            exdiv.innerHTML = workout[i][j][k].exercise;
            exdiv.appendChild(closediv);

            td.appendChild(exdiv);
        }
    }
}

The id works correctly here:

exdiv.id = workout[i][j][k].id;

The id doesn't work when I have it here:

closediv.onclick = function () {
                console.log(workout[i][j][k].id);
            };

Please let me know what I've done wrong

Upvotes: 1

Views: 53

Answers (2)

Gyrocode.com
Gyrocode.com

Reputation: 58910

SOLUTION

Try this code instead:

closediv.onclick = function () {
   console.log(this.parentNode.id);
});

DEMO

See this jsFiddle for demonstration.

Upvotes: 2

jrath
jrath

Reputation: 990

I think its closure loop issue.

if you want to get proper value one of the work around can be :

 closediv.onclick = function () {
     (function(i, j, k) {
         console.log(workout[i][j][k].id);
      )(i, j, k);
 };

Upvotes: 0

Related Questions