1

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

2 Answers 2

2

SOLUTION

Try this code instead:

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

DEMO

See this jsFiddle for demonstration.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.