views:

98

answers:

4

I have created a dynamic list picker script using Jquery 1.3 and PHP that sends a JSON AJAX request and returns a list of items to choose from. The AJAX call works perfectly returning an array of items that I use Jquery to append them as an unordered list to an empty container DIV. That portion of the process works as expected.

The problem comes from the fact that from that list of items, I'm drawing them as links whose clicks are handled by a rel attribute. Here's an example:

<a rel="itemPick" id="5|2" href="#">This is the link</a>

The JQUERY handler looks like:

$('a[rel=itemPick]').click(function () { code here... });

These links and click handlers work fine when the page loads, but when they are appended to the container DIV, the click event does not get picked up. I don't want to have to refresh the entire HTML page again, so is there something I need to do in addition to append() to get JQUERY to recognize the newly added links?

A: 

You need to use live events.

kgiannakakis
+1  A: 
$('a[rel=itemPick]').live("click", function (){ code here... });
DaNieL
A: 

Do you bind the event after adding the links?

Victor
+3  A: 

When you use the jQuery.click method, it's looking for all of the "a" elements that currently exist on the page. Then, when you add a new "a" element, it has no knowledge of that click event handler.

So, there's a new event model in jQuery that allows you to bind functions to all current and future elements called Live Events. You can use Live Events the same way that you use normal event binding, but they will work for all future elements specified. So, you can simply switch your binding logic to:

$('a[rel=itemPick]').live('click', function () {
    //code here...
})
EndangeredMassa
Perfect answer, just a reminder: live cant be applied to those events: blur, focus, mouseenter, mouseleave, change, submit
DaNieL
Wow that's a pretty simple fix. And it worked. Thanks much!
Jeff Fox
@DaNieL: Right! But, I hear that they are working on support for those events in a future release.
EndangeredMassa
@EndangeredMassa: yes, but actually the only way is the jquerylive plugin
DaNieL