0

In my MVC project, on a button click event (in jQuery) I am populating a dynamically created Html ul Li list. It is working fine but when I am using jQuery click event on dynamically created ul Li , it is not working. The code is as follows:

$(document).ready(function() {
     $('ul.cls-ul li').click(function(e) { 
         alert(this);
     }); 
})

Is there any better solution?

Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62
  • Does this answer your question? [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – matthias_h May 04 '20 at 11:40
  • For dynamically created elements, it's necessary to delegate events from parent elements that are already there when the page is initially loaded using on(). Like e.g. $(document).on("click", "ul.cls-ul li", function() { }); – matthias_h May 04 '20 at 11:42

1 Answers1

1

You need change click function format to

$(document).on('click','ul.cls-ul li',function(){
  alert(this);
});
Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62