chowwy
chowwy

Reputation: 1126

jquery toggle individual list item

I am using the function below to toggle comment boxes in an activity feed. What should happen is that the word "Comment" is clicked and the comment box becomes visible.

This is only happening for the first element in the list. If I click on the word "Comment" on any entry besides the first, the first comment_box toggles.

How can I get each comment box to toggle individually? Also, what is this issue called in jQuery? I tried to look it up but didn't know what to call it.

jQuery

$(function(){

    $('span#comment_box').hide();

    $('.comment').click(function() {

    $('#comment_box').toggle();

    });
  });

HTML

<span href="" class="comment">Comment</span><br />
    <span id="comment_box"><textarea name="status_comment"  /></textarea><br /></span>

Here's the jsfiddle - http://jsfiddle.net/jpBE3/

Upvotes: 0

Views: 743

Answers (2)

ShankarSangoli
ShankarSangoli

Reputation: 69905

First of all the id should be unique for each element on the page. May be you have multiple elements with same id so you are facing this issue. jQuery will return the first element which has the required id when you use $('#comment_box').

Instead of id I would suggest you use class and then you can select the element by its class name. You have to use nextAll passing the required selector to find the corresponding element and the call toggle method on it.

Markup change

<span href="" class="comment">Comment</span><br />
<span class="comment_box"><textarea name="status_comment"  /></textarea><br /></span>

JS

  $(function(){
       $('span.comment_box').hide();
       $('.comment').click(function() {
           $(this).nextAll('.comment_box:first').toggle();
       });
  });

Upvotes: 3

Iansen
Iansen

Reputation: 1268

You apparently have more the one elements with the id comment_box .... css ids should be unique on a page. That's why it toggles the first comment_box because it should only be 1 element with the id comment_box on a page. Use class instead of id.

Upvotes: 0

Related Questions