-3

I am trying to invoke a javascript function from some HTML code inserted by some other javascript code (see below).

$(".leave-a-note").click(function() {
            var id = $(this).closest('li').attr('id');
            $('#' + id).children('.write-comment-space').html("<a class='save-comment' href='#' onClick='insertComment();'>Save</a> <a href='#'>Cancel</a>");});

When I try to call a function from the ".save-comment" url nothing happens.

$(".save-comment").click(function() {
            console.log("test");
        });

However, if I leave the ".save-comment" URL directly in my HTML the function works. What am I doing wrong?

user3642173
  • 1,225
  • 5
  • 19
  • 42

1 Answers1

-2

use delegated event like this as html is generated after the DOM is loaded:

$(document).on("click",".save-comment",function() {
            console.log("test");
        });
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160