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.

1

1 Answer 1

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

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

5 Comments

I'm not sure that would work, since I wouldn't be able to get the ID from the rows.
the event object has all the properties of the object that dispatched the click event..including the ID...just do e.target.id
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.
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?
I'm currently trying to. But my stripped down code won't run there.

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.