简体   繁体   中英

how can I toggle a div individually when outputting from a php while loop

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?

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-

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM