1

I have this php script -

$sql = "SELECT * FROM comments WHERE post_id='$id' ORDER BY com_id DESC";
$result = $conn->query($sql);
if ($result->num_rows > 0) {

while($row = $result->fetch_assoc()) {
    $date = $row['date'];
    $mydate = date("M jS g:i a",strtotime($date));
    $user = $row['user'];
    $comment = $row['comment'];
    $reply = $row['reply'];
    $comID = $row['com_id'];

    echo '<div id="comuser">'.$user.': </div>';
    echo '<div id="icomment">'.$comment.'</div>';
    echo '<div id="comdate">'.$mydate.'</div>';
    echo '<div id="replyBTN">reply</div>';

        echo '<form method="post" id="replyForm" action="get_reply.php?reply='.$comID.'">';
        echo '<input type="text" id="addReply" name="addReply" placeholder="add reply">';
        echo '<input type="submit" name="subCom" value="submit">';
        echo '</form>';


}
} else {
    echo "<div id='noCom'>no comments..</div>";
}

I want to echo the div 'replyBTN' and use jquery to toggle the form, here is my jquery click function -

$(document).ready(function(){   
    $("#replyBTN").click(function(){
        $("#replyForm").toggle();
    });
});

It currently will only toggle the first reply button in the first comment, all other reply buttons will not work in the other comments. Why does the jquery only toogle the first reply button?

12
  • 4
    The reason it only works for the first one, is because ID's are unique, so jQuery stops searching for more elements once the first one is found, simply because there can't be more elements with the same ID, it's invalid. Commented Sep 23, 2016 at 0:44
  • 2
    ...therefore, use a class. Commented Sep 23, 2016 at 0:45
  • So will changing to a class fix this? Commented Sep 23, 2016 at 0:46
  • Ahh haa thanks! If you want, post as an answer and ill accept it Commented Sep 23, 2016 at 0:46
  • @RyanD I posted a community wiki answer and you're welcome. I can't take all the credit for this. Adeneo did put in the comment first and I was about to enter something similar. The question can be marked as solved. Commented Sep 23, 2016 at 0:49

1 Answer 1

1

I think this is fit as a community wiki; I've nothing to gain from this, nor do I expect rep gain for it.

Taken from comments:

The reason it only works for the first one, is because ID's are unique, so jQuery stops searching for more elements once the first one is found, simply because there can't be more elements with the same ID, it's invalid. – adeneo

and mine

...therefore, use a class – Fred -ii-

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.