0

On Ajax Success, li element is appended to ul.

$.ajax({
           ..
     success: function (response) {
         response.data.forEach(function (x) {
            $("#ulMain").append('<li class="liSub">' + x + '</li>');
     }
});

It creates sth like this:

<ul>
  <li class="liSub">ABC</li>
  <li class="liSub">BCF</li>
</ul>

I want the dynamically added li elements to fire an alertbox on click. But the code below is not being hit.

$(document).ready(function () {
    $(".liSub").on("click", function () {
        alert("Fired");
    });
});

Interestingly, If I run the document.ready section of the code using F12 - Console, it works. What stops it run normally, and lets it run through console?

Jude
  • 2,135
  • 8
  • 39
  • 64

3 Answers3

2

You missed . prefix for class and use event delgation for created dynamic dom elements

$("ul").on("click", '.liSub', function () {
     alert("Fired");
});
Sudharsan S
  • 14,830
  • 3
  • 27
  • 47
1

Since it is an element loaded dynamically, try delegating it:

$(document).ready(function () {
    $("body").on("click",".liSub", function () {
        alert("Fired");
    });
});
Praveen Kumar Purushothaman
  • 154,660
  • 22
  • 177
  • 226
1

It is because when your page is ready, the ajax call is not finished. You can try this :

$(document).ready(function () {
    $("#ulMain").on("click",".liSub", function () {
        alert("Fired");
    });
});

It will bind the click to the #ulMain which exists at the execution and will delegate the event to .liSub at the moment of the click. It creates only one binding which is also better for global performance.

Pierre Maoui
  • 5,000
  • 1
  • 20
  • 25