Get specific div when clicking button in php while loop

Ryan

New Member
#1
I have a while loop spitting out multiple post which each has a div button called 'flag_btn', when clicked I am trying to show the corresponding div container for my form all being displayed from a PHP while loop -
Mã:
    $sql = "SELECT * FROM table";
    $result = $conn->query($sql);
    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
          $post_id = $row['post_id'];
echo "
<div id='flag_btn'>flag </div>
<div id='flag_cont' style='display:none'>
    <form method='post' class='flag_form'>
        <input type='radio' name='flag_reason' value='off'>Its Offensive<br>
        <input type='submit' value='Submit'>
    </form>
</div>
";
Here is the jquery click event -
Mã:
$('#flag_btn').click(function() {
    $(this).closest('#flag_cont').show(200);
});
But it doesn't work.. How can I get the click event to display just the flag_cont that corresponds to the post that was clicked?

*note: I didnt post the php while loop as I felt it was unnecessary..
 

Admin

Administrator
Thành viên BQT
#2
I think next() is better in this case.

I also replaced id on the "Buttons" with class so it will work for multiple "Buttons".

Mã:
$('.flag_btn').click(function() {
  $(this).next('#flag_cont').show(200);
});
Mã:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='flag_btn'>flag1</div>
<div id='flag_cont' style='display:none'>
  <form method='post' class='flag_form'>
    <input type='radio' name='flag_reason' value='off'>Its Offensive1<br>
    <input type='submit' value='Submit'>
  </form>
</div>
<div class='flag_btn'>flag2 </div>
<div id='flag_cont' style='display:none'>
  <form method='post' class='flag_form'>
    <input type='radio' name='flag_reason' value='off'>Its Offensive2<br>
    <input type='submit' value='Submit'>
  </form>
</div>
<div class='flag_btn'>flag3 </div>
<div id='flag_cont' style='display:none'>
  <form method='post' class='flag_form'>
    <input type='radio' name='flag_reason' value='off'>Its Offensive3<br>
    <input type='submit' value='Submit'>
  </form>
</div>
 
OP
OP
R

Ryan

New Member
#3
Yep that was my problem, I forgot to make the button a class.. And using next instead of closest.. Thanks mate cheers!
 
Top