I'm currently learning JavaScript in school and we aren't using JQuery yet, so I can't use that for this assignment. I am dynamically adding rows to a table in JavaScript, based on JSON data. However, I need to make these rows clickable to then call a function.
This is what I currently have:
var table = document.getElementById("destinations");
for(var i=0; i < myJson.length; i++){
var row = table.insertRow(i+1);
row.insertCell(0).innerHTML = myJson[i]["name"];
row.insertCell(1).innerHTML = myJson[i]["capital"];
row.insertCell(2).innerHTML = myJson[i]["region"];
row.insertCell(3).innerHTML = myJson[i]["surface"];
row.insertCell(4).innerHTML = myJson[i]["population"];
}
How would I go about doing this?
I managed to make the rows clickable by adding an event listener:
row.addEventListener('click', function(){});
An issue that arised when doing this is that every tablerow would call the same function. Only the last tablerow was supposed to call this function. I fixed this by adding the event listener in an anonymous function so now my code looks like this:
var table = document.getElementById("destinations");
for(var i=0; i < myJson.length; i++){
var row = table.insertRow(i+1);
(function (i) {
row.addEventListener('click', function(){});
})(i);
row.insertCell(0).innerHTML = myJson[i]["name"];
row.insertCell(1).innerHTML = myJson[i]["name"];;
row.insertCell(2).innerHTML = myJson[i]["region"];
row.insertCell(3).innerHTML = myJson[i]["surface"];
row.insertCell(4).innerHTML = myJson[i]["population"];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With