I am building a rails application and am having a problem setting the onclick function for each table row. The table gets built dynamically and I would like each row to return an id field for further processing. The problem I am having is each row returns the last id.
Pardon my example at http://jsfiddle.net/vz7beLkg/1/ since it looks like crap. I had to make numerous modifications to get it to work in the fiddle. But it demonstrates the problem I am having. If you click a row in the top section you always get 11. I use a loop to assign counters and it appears a new row gets created because all the counters appear on screen.
for (r = 0; r < 11; r++) {
var newRow = table.insertRow(table.rows.length);
newRow.onclick = function () { gatherImageData(r); };
var newCell = newRow.insertCell(0);
var newText = document.createTextNode(r);
newCell.appendChild(newText);
var newCell = newRow.insertCell(1);
var newText = document.createTextNode('r' + r);
newCell.appendChild(newText);
}
Why does it behave in the way? Without knowing why I may make the same mistake again.
EDIT: The gatherImageData function will create a table in the lower portion of the page based on the id. There will be a list of ids that can change in the upper portion.
EDIT:
I tried using the approach offered by Abdul but it produces the same error; .http://jsfiddle.net/vz7beLkg/5/
I added an assignment to the loop variable after the loop; r = 99. Now all the rows use this value.
How do I use a value in the loop to pass to each rows click event? It seems the click events are being modified after assignment. If I make it loop once the onclick returns 1. If I make it loop twice all rows return 2 (looping 0 then 1 then setting the loop var to 2). So it seems the onclick event is being modified AFTER it is being set with
newRow.onclick = function () { gatherImageData(r); };
How do I stop if from changing OR How do I properly assign it so it does not change AFTER I set it OR Why are all click events the same when a new row object appears to be created?
It seems either a new row object is being created sionce there are new rows in the table. Unless new rows are being inserted but the newRow object is pointing to all of them.