0

I have written code to add table element and I am trying to console log the onclick function of that class that is not working

add

<div>
    <table id="con">
        <tr><td class="delete"> something</td></tr>
    </table>
</div>
<script>
    $("#a").click(function () {
        $("#con").append("<tr> <td class='delete'>something</td></tr>")
    });


    $(".delete").click(function () {
        console.log("clicked");
    })

</script>

1 Answers1

0

It doesn't work because your click-handler only binds to those elements that are already present on the page at the moment when you bind the handler.
What you need is a delegated event.

Read this to understand what you need to do:
https://learn.jquery.com/events/event-delegation/

The gist of it is this:

Change this...

$(".delete").click(function() {
  console.log("clicked");
});

...to this...

$("#con").on("click", ".delete", function() {
  console.log("clicked");
});
myfunkyside
  • 3,890
  • 1
  • 17
  • 32