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>');
});
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>');
});
Share
Improve this question
edited May 23, 2017 at 10:32
CommunityBot
11 silver badge
asked Jun 21, 2014 at 19:52
DiegoDiego
9641 gold badge14 silver badges40 bronze badges
0
2 Answers
Reset to default 6Solution 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.
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() {...