views:

108

answers:

2

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.

+9  A: 

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.

JacobM
That would explain the strange behavior :) In that case I don't see any nice way to use .live() to replace .click()... guess I'll just refresh my plugin after inserting new elements into the DOM, certainly not the end of the world.
asoules
You ought to be able to construct a selector by concatenating the ID of the container (assuming it has one) with the element/class you want. For example, if your container has an ID of "myDiv", then you could do $("#myDiv > a.some_link").live(). You might have to construct that selector string on the fly by doing something like "#" + this.id + " > a.some_link", but that should be possible.
JacobM
+1  A: 

Try something like this. You can't use "live" except on selectors.

$('a.some_link').live('click', function() {
    // some code that submits $form via ajax
});

Hope it helps!

Frankie
The poster may need a more complicated selector than that, since it looks like he's looking for elements that match the selector you gave, but only within the given container. But it's not clear what the container is.
JacobM
@JacobM your right! I do think your answer says it all. Had I seen your post prior to my reply and I probably wont have gone somewhere else! ;)
Frankie