0

How do I add onclick events to elements in a loop? I have tried it like this.

            var c = "#FFFFFF"
            for(var i=0; i<_data.length; i++){
                c = c == "#FFFFFF" ? "#D8D8D8" : "#FFFFFF";

                var row = table.insertRow(rowCount++);
                row.style.backgroundColor = c;
                row.onclick = function(){
                    clickEvent(_data[i][0]);
                }

                newColl(row,i,0,_data[i][1]); //Name
                newColl(row,i,1,_data[i][2]); //Surname
                newColl(row,i,2,_data[i][3]); //Time working

                newColl(row,i,3,""); //TO-DO: Started at
                newColl(row,i,4,""); //TO-DO: Walked home
                newColl(row,i,5,""); //TO-DO: Took lunch
            }

I know that don't work, and I know why. But I don't know how to fix it.

Yemto
  • 613
  • 1
  • 7
  • 18
  • http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – Tmdean Apr 08 '14 at 22:33

1 Answers1

1

DO NOT DO THAT!!!!!. This is the exact reason why Event Delegation exists. Just attach ONE click event to the parent of the elements you are looping through and they should automatically dispatch click events when clicked.

click here for an explanation

shanks
  • 912
  • 10
  • 23
  • I'm not sure that would work, since I wouldn't be able to get the ID from the rows. – Yemto Apr 08 '14 at 22:46
  • 1
    the event object has all the properties of the object that dispatched the click event..including the ID...just do ***e.target.id*** – shanks Apr 08 '14 at 22:48
  • I can't get that to work :/ I tried with setAttribute and ID. But all I get is null, and with the method of using class name, i get an empty string. – Yemto Apr 08 '14 at 23:09
  • Can you put a stripped down version of your code in jsfiddle and share it, i might be able to help if i see how your html markup is structured. Are you creating the rows dynamically in JS? – shanks Apr 08 '14 at 23:12
  • I'm currently trying to. But my stripped down code won't run there. – Yemto Apr 08 '14 at 23:49