Erkan BALABAN
Erkan BALABAN

Reputation: 1376

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?

Upvotes: 3

Views: 688

Answers (2)

rfunduk
rfunduk

Reputation: 30442

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).

Upvotes: 1

Nick Craver
Nick Craver

Reputation: 630579

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.

Upvotes: 5

Related Questions