-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,135
  • 2
  • 17
  • 36

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
  • 60,736
  • 15
  • 100
  • 154