Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically added HTML not being recognized by jQuery

Read some other things on here re: this similar problem but am not sure how to apply this to my dilemma.

I have a jquery function that replaces some HTML in a list.. For example, before the function runs:

<ul id="mylist">
<li id="item1">blah blah blah</li>
<li id="item2">blah blah blah</li>
<li id="item3">blah blah blah</li>
</ul>

Then I have another which runs on click of the LI e.g:

$("#mylist li").click(function () {
alert($(this).attr("id"));
});

Works fine until I dynamically modify the #mylist html, where the alert is blank.

How can I replace the #mylist html and still be able to select the li's found within?

like image 283
Jeff Avatar asked Dec 08 '25 10:12

Jeff


2 Answers

To maintain this functionality on all future dynamically-added list items, you should use event delegation with $.on():

$("#mylist").on("click", "li", function(){
  alert( this.id );
});

Read more about $.on(), online at http://api.jquery.com/on/.

like image 83
Sampson Avatar answered Dec 09 '25 23:12

Sampson


When you replace the contents of #mylist you also remove any event handles that were previously attached to its child li elements.

Instead of the normal click function, try using jQuery's live function:

$("#mylist li").live("click", function() {
    alert($(this).attr("id"));
});

Please note that live events work a bit differently than traditional event, especially when it comes to bubbling and event canceling. If this is a problem, then make sure you reattach click events after you manipulate #mylist.

You might also consider using event delegation. Here's a quick example:

$("#mylist").click(function(e) {
    alert($(e.target).closest("li").attr("id"));
});
like image 20
Xavi Avatar answered Dec 09 '25 23:12

Xavi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!