13

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?

Tipsi
  • 404
  • 4
  • 12
  • 1
    The basic way is `row.addEventListener('click', evt => { ... })`. The advanced way is to add a listener to the whole table instead on individual rows, then check `evt.target` to see where the click originated. – Amadan Jun 14 '19 at 23:55
  • @Amadan That sort of seems to work (Did the basic way). The issue I'm having now is that every row will use the function that only the last row should be using. They all get the same onclick event even though I gave them seperate functions. – Tipsi Jun 15 '19 at 00:11
  • 1
    You are probably doing [this](https://stackoverflow.com/questions/16589806/javascript-click-handler-not-working-as-expected-inside-a-for-loop). It's using jQuery, but basically `$(foo).click(func)` is doing pretty much the same job as `foo.addEventListener('click', func)`. Read that article, and the duplicate it was closed with. – Amadan Jun 15 '19 at 00:14
  • Everything works now, thanks! – Tipsi Jun 15 '19 at 00:20
  • You may want to post the answer to your question, now that you know how to answer it. :) – Amadan Jun 15 '19 at 00:23
  • I guess you don't want to rep – Tipsi Jun 15 '19 at 00:26

1 Answers1

3

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"];
}
Tipsi
  • 404
  • 4
  • 12