jQuery .live('click') only binding to first element on the page

ajax, javascript, jquery

Solution

From the jQuery documentation:

Live events currently only work when used against a selector. For example, this would work: $("li a").live(...) but this would not: $("a", someElement).live(...) and neither would this: $("a").parent().live(...).

In your case, you're calling live() on a variable that's the result of a find() call. That's not a selector. You need to figure out a selector that identifies the elements you want.

Edited to add: for anyone finding this later, the preferred approach now is to use the function `on()` for this. The `on()` function does not have the same restriction -- since it operates on a jQuery object (rather than implicitly binding to the document) it can be set on a set of elements arrived at by chaining as in the original question.

Problem

I wrote a jQuery plugin that binds to 8 elements on a page, and I wanted to use .live() to bind the click action to a link in each element. When you click the link it should post a form using ajax. The problem is that all the links for all 8 elements submit the form for the first element on the page. When I use .click() everything works correctly. I would prefer to use .live() since I will have adding more elements dynamically. Here is some code similar to what I'm doing: ``` var $container = $(this); var $form = $container.find('form.some_form'); var $button = $container.find('a.some_link'); ``` This will only submit the form for the first element: ``` $button .live('click', function() { // some code that submits $form via ajax }); ``` However, this always submits the correct form: ``` $button .click( function() { // identical code that submits $form via ajax }); ``` Is there something about .live() that I should know? Stumped.

Original source