I am just starting off teaching myself Javascript after learning some basics in a university class a year ago. For a web app I am supposed to write, I need to allow users to "select" rows of a table, preferably by clicking on them. I have a strong Python background and my approach probably reeks of GTK paradigms. I have a nagging fear that I'm "reinventing the wheel" somehow by trying to do this when there is a much more standard or accepted way, but like I said, don't know much Javascript yet. My Javascript code to try and do this is:
//Get list of rows in the table
var table = document.getElementById("toppings");
var rows = table.getElementsByTagName("tr");
var selectedRow;
//Row callback; reset the previously selected row and select the new one
function SelectRow(row) {
if (selectedRow !== undefined) {
selectedRow.style.background = "#d8da3d";
}
selectedRow = row;
selectedRow.style.background = "white";
}
//Attach this callback to all rows
for (var i = 0; i < rows.length; i++) {
var idx = i;
rows[idx].addEventListener("click", function(){SelectRow(rows[idx])});
}
This apparently doesn't work because after the loop exits idx is equal to rows.length - 1 so the row argument in SelectRow is rows[rows.length - 1], which is always the last row; that is, the values of i are not "saved" as arguments to the event listener callback. How can I call an event listener with its own saved arguments? This thread seems to give a way to do this with the onclick property, but I understand that this is deprecated and addEventListener (or some monstrous IE-compatible addEvent library) is now the "correct" way to do it.