5

I know it might sound stupid but for some reason I`m having some weird problem.

so, I have a code in js which generate a table with a buttons I gave all buttons same class.

when I try to click on them and use jquery function to console.log something nothing happens.

$.each(data,function(i, d){
    $('#myTable tbody').append(`
        <tr>
            <td>${d.Date}</td>
            <td>${d.Name}</td>
            <td>${d.Score}</td>
            <td><button class='graphXY' data=${d.id}>View</button></td>
        </tr>`);
});

its inside ajax and the table generates good and each button gets class and data good.

now when I try to do

$(".graphXY").click(function(){
    console.log("hit");
})

basically nothing happens and for some reason I cant find the reason.

void
  • 36,090
  • 8
  • 62
  • 107
Talg3017
  • 55
  • 4

1 Answers1

2

The click() binding you're using is called a "direct" binding which will only attach the handler to elements that already exist.

It won't get bound to elements created in the future. To do that, you'll have to create a "delegated" binding by using on().

$("#myTable").on("click", ".graphXY", function(){
    console.log("hit");
})
void
  • 36,090
  • 8
  • 62
  • 107