1

I want to get the value from a dynamically LI I created.

I found this answer which explains how to get it normally.

This is my code. This works perfect for the two elements I have on my LI.

<ul class="nav nav-pills nav-stacked" id="listPreReq" style="height: 200px; overflow: auto" role="menu">
  <li class="active"><a href="#">Action</a></li>
  <li><a href="#">Another action</a></li>
</ul>


$("#listPreReq li").click(function() {    
 alert($(this).html());  
});

But I have this option for adding more elements to the LI. All the new elements I added, they don't fire the $("#listPreReq li").click event. Not sure why. This is a demo.

$('#btPre').click(function(e) {
  var Psize= $("#listPreReq").find("li");
  Psize = Psize.size()+1;
  $("#listPreReq").append('<li><a href="#">Page '+Psize+'</a></li>');
});
Community
  • 1
  • 1
Diego
  • 916
  • 1
  • 13
  • 36

2 Answers2

6

Solution Demo

Instead of binding events to document you can even bind them to ul:

$("#listPreReq").on('click', 'li', function() {    
    alert($(this).html());  
});

Have a look at event delegation.

Niranjan Borawake
  • 1,628
  • 13
  • 20
4

use $(document).on('click','#btPre',function(e) {... instead of $('#btPre').click(function(e) {... and it will be fired! it is called event delegation!

UPDATE: and also this part too:

$("#listPreReq li").click(function() {...

change it to:

$(document).on('click',"#listPreReq li",function() {...
Amin Jafari
  • 7,157
  • 2
  • 18
  • 43
  • It doesn't work. Still it doesn't fire. :http://jsbin.com/fohoca/4/edit $(document).on('click','#btPre',function(e) { – Diego Jun 21 '14 at 19:58