views:

45

answers:

4

I have a link and would like to show/hide ONE form. The first line does it but it does it to ALL forms inside of the one in its own comment div. How do i select the form. the other 3 were guesses and dont work (they seem to do nothing at all). I'm thinking going up to the comment, then down to the form and use toggle on it (as the first line which works but applies to all) would do the trick. But so far it seems i get 0 elements

$('.comment .reply a').click(function() {
    $('.comment form').toggle('slow');
    //$(this).parent('.comment').children('form')[0].toggle('slow');
    //$(this).parent('.comment').find('form').toggle('slow');
    //$("form", this).toggle('slow');
});
+1  A: 

If I understand correctly, this should do it:

$('.comment .reply a').click(function() {
    $(this).closest(".comment").find("form").toggle('slow');
});

That is to say, get the closest parent div of class .comment to the clicked anchor, and find its descendant form element.

karim79
+1 for a great answer!
Doug Neiner
@Doug Neiner - Thanks, but apparently not. I just got down-voted. Would love to know the reason.
karim79
Thats crazy, this is the correct answer provided in the absence of actually seeing the HTML. Based on the original selectors provided, this will work.
Doug Neiner
The weird thing is this didnt work when i copied pasted it (i didnt downvote) but now it does and i have no clue why. +1 and accept.
acidzombie24
Now i see the problem. This is a tree and it does each of the children form too. Can i make it only do the first one it sees? (the highest most and closest)
acidzombie24
A: 

Change that to

$('.comment .reply a').click(function(event)
{
    $(event.target).parent('form').toggle('slow);
});

This will take the target of the event, find the parent form, and toggle it.

Josh K
You should not use `event.target` in a click event unless you know exactly what it means and want to utilize it. Use `this` or its equivalent `event.currentTarget` instead. If the user clicked on a `<strong>` tag inside the `<a>` tag, for instance, your script would fail.
Doug Neiner
Right, but why would you have a `<strong>` tag inside an anchor? Using CSS to style the anchor would be a much better choice, or possibly wrapping the anchor in the strong tag.
Josh K
A: 

You could try

$(this).closest('form').toggle();
Paul Creasey
A: 

Add an id to the form, and use it in the selector.

Tomas Lycken