Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I handle click event of dynamicly populated ul's li?

I am working an authorisation system. I have four unordered lists. Let's name them list1, list2, list3 and list4. two of them about countries and rest two are about cities. list1 contains all countries. list2 contains all available countries for one employee. Users are moving one country from list1 to list2. when user clicks list2 i can handle that event and i am populating city's of this country to list3 with jquery. That city list comes from an aspx web page. I want to handle click event of list4. list4 is containing all available cities for employee. I wrote those lines.

$('#clist2 li').click(function() {
    alert('test');
});

But i did not see the alert. How can i handle click event of list4?

like image 607
Erkan BALABAN Avatar asked Dec 06 '25 11:12

Erkan BALABAN


2 Answers

You can use .delegate() here, like this:

$('#clist2').delegate('li', 'click', function() {
    alert('test');
});

$('#clist2 li') gets all the <li> elements inside #clist2 at that time, instead you can bind a handler to #clist2 directly which listens for the click events from any <li> elements (present or added later, their events bubble the same way) to bubble up.

like image 188
Nick Craver Avatar answered Dec 08 '25 00:12

Nick Craver


You could use .live() to have all lis get click events regardless of whether they exist at the time of binding or not (eg, the selector just has to match).

like image 34
rfunduk Avatar answered Dec 08 '25 00:12

rfunduk



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!