Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In JavaScript how do I make a dynamically created tablerow clickable without using JQuery?

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?

like image 497
Tipsi Avatar asked Jun 14 '19 23:06

Tipsi


1 Answers

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"];
}
like image 105
Tipsi Avatar answered Sep 17 '22 12:09

Tipsi