Angel Grablev
Angel Grablev

Reputation:

Only select a single element that is inside the same element | jQuery selectors

So i have a unordered list, each item in the list has a button that is suppose to toggle the post comment textarea. Unfortunately with my first attempt when u click on one Post Comment button all textareas open, then i tried to use this to make sure only one element is selected. Here is the code:

<ul class="todosDisplay">
 <li><span>Content of todo</span><a class="postComment">Post Comment</a>
     <textarea class="showMe"></textarea>
 </li>
<li><span>Content of todo</span><a class="postComment">Post Comment</a>
     <textarea class="showMe"></textarea>
 </li>
<li><span>Content of todo</span><a class="postComment">Post Comment</a>
     <textarea class="showMe"></textarea>
 </li>
 </ul>

And here is my jquery code

$(".postComment").click(function () { 
          $(this).parent().find(".showMe").toggle();
        });

As you can see my poor man's attempt to get to the parent of the ACTUAL element, and then find the element we need to toggle does not work :)

Thanks a lot in advance!

Upvotes: 1

Views: 970

Answers (3)

Jojo
Jojo

Reputation: 348

I would suggest changing the jQuery to:

$(".postComment").click(function(){ 
   $(this).siblings(".showMe").toggle();
   return false;
});

Upvotes: 0

NJE
NJE

Reputation: 769

Just built this in Visual Studio and it seems to work. The only thing I noticed with the example above was that the href was missing from the anchor tags resulting in IE not rendering them as links. I added href="#" and your code seemed to work for me. Clicking the link would close the textarea correctly.

<script type="text/javascript">
    $(document).ready(function() {

        $(".postComment").click(function() { $(this).parent().find(".showMe").toggle(); });

    });
</script>

<ul class="todosDisplay">
    <li><span>Content of todo</span><a class="postComment" href="#">Post Comment</a>
        <textarea class="showMe"></textarea>
    </li>
    <li><span>Content of todo</span><a class="postComment" href="#">Post Comment</a>
        <textarea class="showMe"></textarea>
    </li>
    <li><span>Content of todo</span><a class="postComment" href="#">Post Comment</a>
        <textarea class="showMe"></textarea>
    </li>
</ul>

Upvotes: 0

helloandre
helloandre

Reputation: 10721

you can use jQuery's $.closest(".showMe") function.

Upvotes: 1

Related Questions